212

This question already has an answer here:

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

9 답변


262

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.


  • Note that in general the finally block will check for nullity before calling Dispose. Not that it matters when you're calling a constructor, but... - Jon Skeet
  • If you declare the variable outside the using block and then create a new instance in the using statement it may not dispose the item. - John
  • So the using statement will automatically dispose of the object once that context is complete, WHEN should we use the using statement then, on types that implement IDisposable? Which types must implement that interface, is there any sort of rule of thumb on this or do I have to check each type individually? - JsonStatham
  • Being pedantic you need curly braces around your second code block to reflect the limited scope. - Caltor
  • Note: watch out for using the using block with HttpClient()! See this article. - jbyrd

90

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.


  • Is null check necessary ? How can mine be null after "new MyClass()"; The only thing i can see is a OutOfMemoryException but in that case it shouldn't even enter the try block right ? EDIT : you probably wrote this to show what is done usually when using is used. Inside the using, there might be something else than a new constructor call (eg : a method call that return null) - tigrou
  • well, you could do other things than mine.Action(). Things like mine=null. Without using mine can be set to anything in the try/catch - Sam

39

From MSDN:

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

In other words, the using statement tells .NET to release the object specified in the using block once it is no longer needed.


  • This gives the rationale for using "using", while @plinth shows what it actually does. - tvanfosson
  • Indeed. This is the answer to "What is the purpose of the Using block in C#?" - Robert S.
  • @tvanfosson: FYI, the ampersand character is meant to imply that you are directing your comment at a user, as I've done at the beginning of this comment. You don't need to prefix every reference to another user with this character as you did when you mentioned plinth. - raven
  • @raven: FYI, that's not an ampersand, this is: & :) - Scott Ferguson

19

The using statement is used to work with an object in C# that implements the IDisposable interface.

The IDisposable interface has one public method called Dispose that is used to dispose of the object. When we use the using statement, we don't need to explicitly dispose of the object in the code, the using statement takes care of it.

using (SqlConnection conn = new SqlConnection())
{

}

When we use the above block, internally the code is generated like this:

SqlConnection conn = new SqlConnection() 
try
{

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

For more details read: Understanding the 'using' statement in C#.


5

Placing code in a using block ensures that the objects are disposed (though not necessarily collected) as soon as control leaves the block.


5

Also take note that the object instantiated via using is read-only within the using block. Refer to the official C# reference here.


5

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

is equivalent to

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


  • This answer contains a typo. (And that is another example of why we should name our classes right in the first place.) Please refer to the other answer in this post. - RayLuo

2

It is really just some syntatic sugar that does not require you to explicity call Dispose on members that implement IDisposable.


2

The using statement obtains one or more resources, executes a statement, and then disposes of the resource.

Linked


Related

Latest