Search code examples
c#disposeusingusing-statement

Does "using" statement always dispose the object?


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();
}

Solution

  • 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.