Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If an exception occurs inside a "using" block, is the Dispose method called? [duplicate]

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

like image 794
Brij Avatar asked Feb 03 '14 17:02

Brij


People also ask

What happens if an exception is thrown in using block?

The exception is thrown, because there is no catch statement in the compiled code. If you handle the exception within the using block, your object will still be disposed in the compiler-generated finally block.

Is dispose called if exception thrown?

The answer is no. Dispose() does not get called in the attached code. Further more the exception that is thrown is not handled and the program blows up.

Does using block call Dispose C#?

What is the use of using statement in C# ? Placing your code inside a using block ensures that it calls Dispose() method after the using-block is over, even if the code throws an exception.


1 Answers

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();
    }
}
like image 189
Habib Avatar answered Sep 28 '22 05:09

Habib