Monday, January 10, 2011

Why use "using" instead of calling the "Dispose" method directly?

The following statement:

using(disposable) { }

Has 2 main advantages over the alternative:

disposable.Dispose();

  • It handles null variables gracefully
  • It can be easily extended so you can use

using(disposable1)
using(disposable2) { }


instead of

try
{
disposable1.Dispose();
}
finally
{
disposable2.Dispose();
}

No comments: