DUPE: 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";
}
You can use
using
when theSomething
class implements IDisposable. It ensures that the object is disposed correctly even if you hit an exception inside theusing
block.ie, You don't have to manually handle potential exceptions just to call
Dispose
, theusing
block will do it for you automatically.It is equivalent to this:
The using statement has the beneficial effect of disposing whatever is in the () when you complete the using block.
Using gets translated into
when compiling (so in IL).
So basically you should use it with every object that implements
IDisposable
.Using translates, roughly, to:
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.
The using statement ensures that Dispose() is called even if an exception occurs while you are calling methods on the object.
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.