Does "using" statement always dispose the object?

Guillermo Gutiérrez picture Guillermo Gutiérrez · Jun 28, 2013 · Viewed 16.8k times · Source

Does the using statement always dispose the object, even if there is a return or an exception is thrown inside it? I.E.:

using (var myClassInstance = new MyClass())
{
    // ...
    return;
}

or

using (var myClassInstance = new MyClass())
{
    // ...
    throw new UnexplainedAndAnnoyingException();
}

Answer

Ed S. picture Ed S. · Jun 28, 2013

Yes, that's the whole point. It compiles down to:

SomeDisposableType obj = new SomeDisposableType();
try
{
    // use obj
}
finally
{
    if (obj != null) 
        ((IDisposable)obj).Dispose();
}

Be careful about your terminology here; the object itself is not deallocated. The Dispose() method is called and, typically, unmanaged resources are released.