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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With