The C # s Usage Operator provides a syntax shortcut for calling Dispose on objects that implement IDisposable using a try / finally block. For instance:
using (FileStream fs = new FileStream ("myFile.txt", FileMode.Open)) {
The compiler converts this value 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 in case of exception 1, or that the code exits the block earlier.
Thus, to use one block, only the removal of one disposable object will be ensured. on the other hand, you can use nested operators. as
using (myDisposable d = new myDisposable()) { using(Disposable2 d2 = new Disposable2()) {
and it 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(); }
source share