using statement

Mon, July 3, 2006, 06:35 AM under dotNET
The using statement has been in C# for ever and was newly added to VB8 as well (Using). I hope everybody is familiar with it by now (not to be confused with the using directive typically appearing at the top of code files - Imports in VB). If I asked you to tell me about the using statement, I bet that most of you would use a code example , maybe something like the following.

Given a class like this:
class SomeType : IDisposable{
public SomeType(){
// do some ctor stuff
}

public void DoSomething(){
// do some useful stuff
}

public void Dispose(){
// clean up unmanaged resources
}
}
We know that the client code should use it like this:
SomeType st = new SomeType();
try
{
st.DoSomething();
}
finally
{
st.Dispose();
}
The using statement makes that cleaner, easier to remember and easier to enforce like this:
using (SomeType st = new SomeType())
{
st.DoSomething();
}
So, the easy way to describe the purpose of using (without a code example) is this:
The using statement offers an elegant way of ensuring that the developer does not forget to call Dispose on an object that (directly or indirectly) holds unmanaged resources. (My links to msdn at the top pretty much say the same thing)

Effectively, we all associate the using statement (or at least I always did) with not leaking. However, if we look at the using statement not from an intent point of view but instead from a practical point of view, we would probably come up with this:
The using statement accepts as an argument an object that implements IDisposable; it defines a coding block where the ctor of the said object is called at the start and the Dispose method is called in the end.

Next, we'll see how to take that last statement further to describe a design pattern.