using ‘using’ and scope. Not try finally!
Posted
by Edward Boyle
on Techlexic
See other posts from Techlexic
or by Edward Boyle
Published on Sat, 20 Nov 2010 20:36:01 +0000
Indexed on
2010/12/06
17:01 UTC
Read the original article
Hit count: 859
c#
|Visual Studio
An object that implements IDisposable
has, you guessed it, a Dispose()
method. In the code you write you should both declare and instantiate any object that implements IDisposable
with the using
statement. The using
statement allows you to set the scope of an object and when your code exits that scope, the object will be disposed of. Note that when an exception occurs, this will pull your code out of scope, so it still forces a Dispose()
using (mObject o = new mObject()) { // do stuff } //<- out of Scope, object is disposed. // Note that you can also use multiple objects using // the using statement if of the same type: using (mObject o = new mObject(), o2 = new mObject(), o3 = new mObject()) { // do stuff } //<- out of Scope, objects are disposed.
What about try{ }finally{}
?
It is not needed when you use the using
statement. Additionally, using
is preferred, Microsoft’s own documents put it this way:
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.
When I started out in .NET I had a very bad habit of not using the using
statement. As a result I ran into what many developers do:
#region BAD CODE - DO NOT DO try { mObject o = new mObject(); //do stuff } finally { o.Dispose(); // error - o is out of scope, no such object. } // and here is what I find on blogs all over the place as a solution // pox upon them for creating bad habits. mObject o = new mObject(); try { //do stuff } finally { o.Dispose(); } #endregion
So when should I use the using
statement?
Very simple rule, if an object implements IDisposable
, use it. This of course does not apply if the object is going to be used as a global object outside of a method. If that is the case, don’t forget to dispose of the object in code somewhere.
try{}finally{}
code block is not going to break your code, nor cause memory leaks. It is perfectly acceptable coding practice, just not best coding practice in C#. This is how VB.NET developers must code, as there is no using
equivalent for them to use.© Techlexic or respective owner