Search code examples
c#.netusing

What gets disposed when "using" keyword is used


Let's have an example:

using (var someObject = new SomeObject())
{
    var someOtherObject = new SomeOtherObject();
    someOtherObject.someMethod(); 
}

SomeOtherObject also implements IDisposable. Will be SomeOtherObject also disposed when SomeObject get disposed ? What will happen to the SomeOtherObject ? (disposing of SomeOtherObject is not implemented in the Dispose method of SomeObject)


Solution

  • No. Only fields in the using clause will be disposed. In your case only someObject.

    Basically that code gets translated into

    var someObject = null;
    try
    {
      someObject = new SomeObject()
    
      var someOtherObject = new SomeOtherObject();
      someOtherObject.someMethod(); 
    }
    finally
    {
      if (someObject != null )
      someObject.Dispose()
    }