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...