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


Question

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

1
247
5/29/2018 10:03:20 AM

Accepted Answer

If the type implements IDisposable, it automatically disposes it.

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.

302
11/13/2018 5:22:43 AM

Using calls Dispose() after the using-block is left, even if the code throws an exception.

So you usually use using for classes that require cleaning up after them, like IO.

So, this using block:

using (MyClass mine = new MyClass())
{
  mine.Action();
}

would do the same as:

MyClass mine = new MyClass();
try
{
  mine.Action();
}
finally
{
  if (mine != null)
    mine.Dispose();
}

Using using is way shorter and easier to read.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon