6

Possible Duplicates:
Using the using statment in c#
What is the C# Using block and why should I use it?

Just wondering what this means? I've seen lots of tutorials online that have the syntax:

using (SqlCeCommand cmd2 = new SqlCeCommand("SELECT city FROM cities JOIN states ON states.id=cities.state WHERE states.state='" + read.GetString(0) + "'", con))
{
  SqlCeDataReader readCities = cmd2.ExecuteReader();
  while (readCities.Read())
  {
    parent.Nodes.Add(readCities.GetString(0));
  }
}

Why is it used? I tried searching Google, but it comes up with the 'using' keyword which is used for including dll's and other files.

8
  • 11
    See section 8.13 of the C# specification. Jan 25, 2010 at 23:54
  • 2
    See this answer: stackoverflow.com/questions/614959/…
    – AdamW
    Jan 25, 2010 at 23:54
  • 2
    You could also try a quick search here on SO, and you'd have found you've created a duplicate question. Jan 26, 2010 at 0:23
  • 1
    Zano: It might not have helped him much here, depending on whether he knew what he was looking for. In C# the "using" keyword has two completely different meanings.
    – Ken
    Jan 26, 2010 at 6:54
  • 1
    I doubt that most developers even realize the c# specification exists.
    – Greg
    Jan 27, 2010 at 21:07

8 Answers 8

33

The using statement

using(var disposableObject = new object_that_implements_IDisposable()) { ... }

is syntactic sugar for code similar to following:

var disposableObject = new object_that_implements_IDisposable()
try
{
    ...
}
finally
{
    if(disposableObject != null)
    {
        ((IDisposable)your_object).Dispose();
    }
}

This is only applicable for classes that implement IDisposable. It is helpful for cleaning up code where you have objects that take, for example, system resources (file handles, database connections, sockets, etc.) that need to be cleaned up after you are done to free the resource for the rest of the system.

In theory, you could leave out the .Dispose() call, but then you would have to wait for the Garbage Collector to free the kept resources. The GC is awesome at knowing when to free objects to reclaim their memory usage, but it has no idea that it needs to free objects to have them give up other system resources. Thus, these critical resources might not be given up until after the GC decides it needs the memory used by the owner. Thus, you definitely want to dispose of your objects when you are done with them (if they are disposable)!

As to why you'd use using over try/finally, it is purely a coder's preference. I prefer using because you can cascade them:

using(var a = new class())
using(var b = new class())
using(var c = new class())
using(var d = new class())
{
    ...
}

You'd need quite a few more lines of code to do that with try/finally.

using has additional advantages as well. For example, whereas calling x.Dispose directly might throw a NullReferenceException if x is null, using(x) will not.

See also:

3
  • The key is "you would have to wait for the Garbage Collector to free the kept resources." +1 Jan 25, 2010 at 23:59
  • 2
    When leaving a using block, IDisposable.Dispose will be called. This may be different than your object's defined Dispose method if you have also defined IDisposable.Dispose explicitly. Jan 26, 2010 at 1:12
  • Thanks for edit fixing placement of declaration and initialization of variable before the try. Removed my comment pointing out the flaw.
    – GBegen
    Jan 27, 2010 at 18:29
4

The using just instructs the compiler to write code that will call the Dispose method on the variable you're using. Only types that implement 'IDisposable' can be used with using statements.

In your example, cmd2 will be disposed when the code in the {} finishes.

1
  • OK, I understand that, but why is it worded like that? In my mind, using doesn't convey Hey Compiler please clean up after me?
    – FoxDeploy
    Jul 18, 2017 at 1:30
2

"Defines a scope, outside of which an object or objects will be disposed"
See using statement

2

using is applied to objects that implement IDisposable. It ensures that, when leaving the using block (whether normally, or via an exception, or whatever), the disposable object's Dispose method is called.

0

Using statement is defines a scope, that outside of it the object or objects will be disposed.

0

See http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx

The using statement encapsulates variables inside of it in a scope. When the execution exits the using block, all objects inside of it are disposed from memory. You might see it with DB connections so that when the using block exits the resources allocated to that connection are cleaned up and closed.

0

The using statement defines a scope in which to use an object which implements the IDisposable interface. The object will be cleaned up once the block has been exited. See:

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

1
  • always one that implements IDisposable Jan 27, 2010 at 20:32
-1

Using is a cool way of cleaning up resources, it is equivalent to try{}catch{}finally{dispose}. Effective c# has an item on this and I bet you willget 10+ similar answers.

http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660

Not the answer you're looking for? Browse other questions tagged or ask your own question.