Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 914
Fabio Marcolini Avatar asked Jun 26 '13 10:06

Fabio Marcolini


People also ask

Does a Using statement dispose?

The using declaration calls the Dispose method on the object in the correct way when it goes out of scope. The using statement causes the object itself to go out of scope as soon as Dispose is called.

What statement describes a Dispose method?

C# provides a special "using" statement to call Dispose method explicitly. using statement gives you a proper way to call the Dispose method on the object. In using statement, we instantiate an object in the statement. At the end of using statement block, it automatically calls the Dispose method.

Why do we have the Dispose () method?

The Dispose() methodThe Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.

What does using in C# do?

In C#, the using keyword has two purposes: The first is the using directive, which is used to import namespaces at the top of a code file. The second is the using statement. C# 8 using statements ensure that classes that implement the IDisposable interface call their dispose method.


1 Answers

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.

like image 79
Andrei Avatar answered Sep 25 '22 22:09

Andrei