Let\'s say I have a disposable object MyDisposable
whom take as a constructor parameter another disposable object.
using(MyDisposable myDisposab
C#’s using statement provides a syntactic shortcut for calling Dispose on objects that implement IDisposable, using a try/finally block. For example:
using (FileStream fs = new FileStream ("myFile.txt", FileMode.Open))
{
// ... Write to the file ...
}
The compiler converts this to: FileStream fs = new FileStream ("myFile.txt", FileMode.Open);
try
{
// ... Write to the file ...
}
finally
{
if (fs != null) ((IDisposable)fs).Dispose();
}
The finally block ensures that the Dispose method is called even when an exception is thrown,1 or the code exits the block early.
So for using single block will only ensure that the single disposable object will be disposed. on the other hand you can use a nested using statements. like
using (myDisposable d = new myDisposable())
{
using(Disposable2 d2 = new Disposable2())
{
// do something and dispose...
}
}
and this will be converted as
try
{
// work around for myDisposable
try
{
// work around for Disposable2
}
finally
{
if (d2 != null)
((IDisposable)d2 ).Dispose();
}
}
finally
{
if (d!= null)
((IDisposable)d).Dispose();
}