Search code examples
c#idisposableusing

Does the using statement dispose only the first variable it create?


Let's say I have a disposable object MyDisposable whom take as a constructor parameter another disposable object.

using(MyDisposable myDisposable= new MyDisposable(new AnotherDisposable()))
{
     //whatever
}

Assuming myDisposable don't dispose the AnotherDisposable inside it's dispose method.

Does this only dispose correctly myDisposable? or it dispose the AnotherDisposable too?


Solution

  • using is an equivalent of

    MyDisposable myDisposable = new MyDisposable(new AnotherDisposable());
    try
    {
        //whatever
    }
    finally
    {
        if (myDisposable != null)
            myDisposable.Dispose();
    }
    

    Thus, if myDisposable does not call Dispose on AnotherDisposable, using won't call it either.