Question

In C#, if an exception occurs inside a "using" block, does the Dispose method get called?

Was it helpful?

Solution

Yes it will get called.

using translates into try-finally block, so even in case of recoverable exception Dispose gets called.

See: using statement C#

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

Consider SqlConnection which implements IDisposable interface, so the following:

using (SqlConnection conn = new SqlConnection("connectionstring"))
{
    //some work
}

Would get translated into

{
    SqlConnection conn = new SqlConnection("connectionstring");
    try
    {
        //somework
    }
    finally
    {
        if (conn != null)
            ((IDisposable)conn).Dispose(); //conn.Dispose();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top