C# Basics: On the Importance of the Using Statement and IDisposable

The world of .NET programming is full of objects that implement the IDisposable interface. File, Font, DataContext, Stream, DbConnection, and many more—all implement the IDisposable interface. And for good reason. They touch the outside world and the outside world is messy, full of resource allocations that can only be used one at a time and must be explicitly returned to their owner to be used by another caller.

So in this 8th installment of C# Basics, let’s take a look at how best to use the IDisposable interface by simply using the using statement. The using statement is really just syntactic sugar but it helps you produce much more readable and reliable code.

using (var myobj = new MyDisposable())
{
  myobj.DoSomething();
}

You can even stack them like this:

using (var myobj = new MyDisposable())
using (var otherobj = new MyOtherDisposable())
{
  var x = myobj.DoSomething();
  otherobj.DoAnotherThing(x);
}

Of course, you could write your own resource cleanup explicitly, but it can start to look a bit messy and as lazy as we often are, the cleanup often gets forgotten.

var myobj = new MyDisposable();
var otherobj = new MyOtherDisposable();
try
{
  var x = myobj.DoSomething();
  otherobj.DoAnotherThing(x);
}
finally
{
  if (otherobj != null) otherobj.Dispose();
  if (myobj != null) myobj.Dispose();
}

Use the using statement where you can. It's not a one size fits all syntax sugar, but it is sweet where it fits.