Click here to Skip to main content
Click here to Skip to main content

Use Using!

By , 8 Oct 2010
 
This is probably an obvious tip to most seasoned C# developers, but I often come across people posting code that doesn't handle cleanup properly in the event of an error. (or not at all!)
 
Any object that implements IDisposable can be wrapped with a using statement as follows:
using(IDisposable x = ...)
{
   // do something with x
}
 
The using statement guarantees that the object will be disposed, even if something goes wrong or if the scope is otherwise exited.
 
A sample mistake is something like this (simplified for demonstration, this is NOT good code!)
 
public string ReadHtml(string url) {
        System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)WebRequest.Create(url);
        System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)wr.GetResponse();
 
        System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
        return sr.ReadToEnd();
}
 
Now, because this is such a simple demo, you and I can see that the return statement happens before the stream is closed, but when conditional logic is used, this can be much less obvious.
 
If, instead, this code was written as
 
public string ReadHtml(string url) {
        System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)WebRequest.Create(url);
        System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)wr.GetResponse();
 
        using(System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) {
            return sr.ReadToEnd();
       }
}
 
then the stream would be properly disposed.
 
It's an easy syntax to use and can avoid performance problems when your code goes into production.
 
Note:
using(...) {} is functionally equivalent to
IDisposable x = ...;
try {
 
} finally { x.Dispose(); }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Nathan Staudt
Web Developer
United Kingdom United Kingdom
Member
I've been a web application developer since the late 1990s, working for eCommerce, media and telecoms companies across europe and america.
 
I have a BSc (Hons) in computing from Middlesex University and took a few MCP exams several years ago too.
 
Born in America, I grew up in Ireland. My father encouraged my interest in computers as a child when he would bring home his "portable" ibm pc... (20kg or something like that) and I first wrote some stuff in QBasic aged seven or eight, but my real interest in computers took off when my family got internet access at home in the early 90s.
 
Feel free to email me Smile | :)

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Answer"using" can even deal with null objects and it does not need to be assigned neither...memberAndreas Gieriet27 Jun '12 - 10:35 
There might be situations where you don't know if an object is IDisposable or where the IDisposable object at hand might be null. This is gracefully handled by the using construct.
 
Dealing with null objects: works gracefully - no need to treat them differently
using (var x = null) // usually, this null is rather a result of some function 
{
   ...
}
 
As a result of that, one can handle the situation where an object might or might not be IDisposable.
 
What if not known if an object is ready for using construct? No problem, use the as keyword.
using (var x = GetSomeObject(...) as IDisposable) // if not IDisposable, null is passed to using
{
   ...
}
 
Finally, there may be situations where the object is not accessed at all in the using-block. You may leave the explicit declaration away.
 
You may leave the declaration away: declaration not needed if the object is not accessed in the block.
 
using (AcquireResource()) // the Disopse() function will release the resource
{
   ...
}
 
See also RAII (Resource Acquisition Is Initialization) C# Helper Classes[^] for some example where resource acquisition is the only purpose of the using block.
 
Cheers
Andi
GeneralReason for my vote of 5 nice onemembernikhi _singh22 Feb '12 - 17:37 
Reason for my vote of 5
nice one
GeneralThis is just being picky, but the final note is not quite tr...mvpOriginalGriff27 Dec '11 - 1:00 
This is just being picky, but the final note is not quite true: the using block also causes the IDisposable object to go out of scope, which the try...finally block does not. It is legal (but very stupid) to write:
IDisposable x = ...;
try
{
...
}
finally { x.Dispose(); }
x.Read();
Which you cannot do with the equivalent using block.
Still gets a five though Smile | :)
GeneralReason for my vote of 5 My Vote of 5 Good one :)mvpRaviRanjankr21 Jul '11 - 10:00 
Reason for my vote of 5
My Vote of 5
Good one Smile | :)
GeneralReason for my vote of 5 thanks!memberxzz019513 Oct '10 - 21:40 
Reason for my vote of 5
thanks!
GeneralI was not aware of this until fairly recently, when I ran so...memberMatt U.9 Oct '10 - 8:40 
I was not aware of this until fairly recently, when I ran some old code through VS 2010's code analysis. I researched the issue and realized what I did wrong. Most definitely something that is too often left out. :-P
GeneralI agree. Way too often forgotten :-(memberKelvin Armstrong8 Oct '10 - 11:52 
I agree. Way too often forgotten Frown | :-(
GeneralReason for my vote of 5 very good tip, too often forgottenmemberHerre Kuijpers8 Oct '10 - 8:39 
Reason for my vote of 5
very good tip, too often forgotten

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 8 Oct 2010
Article Copyright 2010 by Nathan Staudt
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid