The using declaration
The using
declaration is a very convenient syntax equivalent to the try/finally
block and provides a deterministic call to the Dispose
method. This declaration can be used on all the objects implementing the IDisposable
interface:
class DisposableClass : IDisposable { Â Â Â Â public void Dispose() => Console.WriteLine("Dispose!"); }
We already know that the using
declaration deterministically invokes the Dispose
method as soon as its closing curly brace is encountered:
void SomeMethod() { Â Â Â Â using (var x = new DisposableClass()) Â Â Â Â { Â Â Â Â Â Â Â Â //... Â Â Â Â } // Dispose is called }
Every time multiple disposable objects need to be used in the same scope, the nested using
declarations are nested, causing an annoying triangle-shaped code alignment:
using (var x = new Disposable1()) { Â Â Â Â using (var y = new...