views:

322

answers:

7

DUPE: http://stackoverflow.com/questions/75401/uses-of-using-in-c

I have seen people use the following and I am wondering what is its purpose? Is it so the object is destroyed after its use by garbage collection?

Example:

using (Something mySomething = new Something()) {
  mySomething.someProp = "Hey";
}
+2  A: 

The using statement has the beneficial effect of disposing whatever is in the () when you complete the using block.

Jason Punyon
+4  A: 

The using statement ensures that Dispose() is called even if an exception occurs while you are calling methods on the object.

Elroy
+2  A: 

You can use using when the Something class implements IDisposable. It ensures that the object is disposed correctly even if you hit an exception inside the using block.

ie, You don't have to manually handle potential exceptions just to call Dispose, the using block will do it for you automatically.

It is equivalent to this:

Something mySomething = new Something();
try
{
   // this is what's inside your using block
}
finally
{
    if (mySomething != null)
    {
        mySomething.Dispose();
    }
}
LukeH
+6  A: 

Using translates, roughly, to:

Something mySomething = new Something();
try
{
  something.someProp = "Hey";
}
finally
{
  if(mySomething != null)
  {
    mySomething.Dispose();
  }
}

And that's pretty much it. The purpose is to support deterministic disposal, something that C# does not have because it's a garbage collected language. The using / Disposal patterns give programmers a way to specify exactly when a type cleans up its resources.

Randolpho
@Randolpho, Not quite. The object is instantiated outside of the try...finally block. If the object fails to instantiate then it can't/doesn't need to be disposed.
LukeH
@Randolpho, And the generated IL will also check that the object isn't null before attempting to call Dispose.
LukeH
Good points, Luke. I did preface with "roughly", remember.;)
Randolpho
@Randolpho, I wasn't trying to be picky, I just thought I'd point it out because yours is currently the top rated answer, so a lot of people might end up reading it. :)
LukeH
Well, I've corrected it. I was more interested in explaining the purpose and context with my post, though, as that's frequently lost on folks.
Randolpho
A: 

Here's a link with an explanation. Mainly for calling Dispose

OTisler
+1  A: 

Using gets translated into

try
{
   ...
}
finally
{
   myObj.Dispose();
}

when compiling (so in IL).

So basically you should use it with every object that implements IDisposable.

Gerrie Schenck
A: 

The 'using' block is a way to guarantee the 'dispose' method of an object is called when exiting the block.

It's useful because you might exit that block normally, because of breaks, because you returned, or because of an exception.

You can do the same thing with 'try/finally', but 'using' makes it clearer what you mean and doesn't require a variable declared outside th block.

Strilanc