What is the C# Using block and why should I use it?

Ryan Michela picture Ryan Michela · Oct 17, 2008 · Viewed 305k times · Source

What is the purpose of the Using block in C#? How is it different from a local variable?

Answer

plinth picture plinth · Oct 17, 2008

If the type implements IDisposable, it automatically disposes that type.

Given:

public class SomeDisposableType : IDisposable
{
   ...implmentation details...
}

These are equivalent:

SomeDisposableType t = new SomeDisposableType();
try {
    OperateOnType(t);
}
finally {
    if (t != null) {
        ((IDisposable)t).Dispose();
    }
}
using (SomeDisposableType u = new SomeDisposableType()) {
    OperateOnType(u);
}

The second is easier to read and maintain.