Coder Perfect

What is the purpose of the C# Using block, and should I use it? [duplicate]

Problem

In C#, what is the use of the Using block? What sets it apart from a local variable?

Asked by Ryan Michela

Solution #1

If a type implements IDisposable, it disposes of itself automatically.

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 simpler to read and keep up with.

There’s a new syntax for utilizing that’s been around since C# 8, and it may allow for better understandable code:

using var x = new SomeDisposableType();

It doesn’t have a { } block of its own and the scope of the using is from the point of declaration to the end of the block it is declared in. It means you can avoid stuff like:

string x = null;
using(var someReader = ...)
{
  x = someReader.Read();
}

And have this:

using var someReader = ...;
string x = someReader.Read();

Answered by plinth

Solution #2

Even if the code throws an exception, Using calls Dispose() when the using-block is removed.

As a result, you normally use using for classes that require cleanup, such as IO.

So, here’s how you use this block:

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

would act in the same way as:

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

Using is a lot shorter and easier to read than using.

Answered by Sam

Solution #3

From MSDN:

To put it another way, the using statement instructs.NET to release the object provided in the using block when it is no longer required.

Answered by Robert S.

Solution #4

When working with a C# object that implements the IDisposable interface, the using statement is utilized.

The Dispose public method on the IDisposable interface is used to dispose of the item. We don’t need to explicitly dispose of the object in the code when we use the using statement because the using statement takes care of it.

using (SqlConnection conn = new SqlConnection())
{

}

When we use the aforementioned block, the code created inside looks like this:

SqlConnection conn = new SqlConnection() 
try
{

}
finally
{
    // calls the dispose method of the conn object
}

Read Understanding the ‘using’ declaration in C# for further information.

Answered by Sunquick

Solution #5

using (B a = new B())
{
   DoSomethingWith(a);
}

is equivalent to

B a = new B();
try
{
  DoSomethingWith(a);
}
finally
{
   ((IDisposable)a).Dispose();
}

Answered by Bert Huijben

Post is based on https://stackoverflow.com/questions/212198/what-is-the-c-sharp-using-block-and-why-should-i-use-it