Does “using” statement always dispose the object?

后端 未结 3 899
渐次进展
渐次进展 2020-12-16 10:04

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 myClassInsta         


        
3条回答
  •  无人及你
    2020-12-16 10:55

    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.

提交回复
热议问题