Click here to Skip to main content
15,173,818 members
Articles / Programming Languages / C#
Posted 8 Oct 2010

Tagged as


11 bookmarked

Use Using!

Rate me:
Please Sign up or sign in to vote.
4.94/5 (20 votes)
8 Oct 2010CPOL
The c# using syntax is often overlooked
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.

using(...) {} is functionally equivalent to
IDisposable x = ...;
try {

} finally { x.Dispose(); }


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


About the Author

Nathan St
Web Developer
United Kingdom United Kingdom
I've been a web application developer since the late 1990s, working for eCommerce, media and telecoms companies across europe and america.

Comments and Discussions

Answer"using" can even deal with null objects and it does not need to be assigned neither... Pin
Andreas Gieriet27-Jun-12 11:35
professionalAndreas Gieriet27-Jun-12 11:35 
GeneralReason for my vote of 5 nice one Pin
Nikhil_S22-Feb-12 18:37
professionalNikhil_S22-Feb-12 18:37 
GeneralThis is just being picky, but the final note is not quite tr... Pin
OriginalGriff27-Dec-11 2:00
mveOriginalGriff27-Dec-11 2:00 
GeneralReason for my vote of 5 My Vote of 5 Good one :) Pin
RaviRanjanKr21-Jul-11 11:00
professionalRaviRanjanKr21-Jul-11 11:00 
GeneralReason for my vote of 5 thanks! Pin
Your Display Name Here13-Oct-10 22:40
MemberYour Display Name Here13-Oct-10 22:40 
GeneralI was not aware of this until fairly recently, when I ran so... Pin
Matt U.9-Oct-10 9:40
MemberMatt U.9-Oct-10 9:40 
GeneralI agree. Way too often forgotten :-( Pin
Kelvin Armstrong8-Oct-10 12:52
MemberKelvin Armstrong8-Oct-10 12:52 
GeneralReason for my vote of 5 very good tip, too often forgotten Pin
Herre Kuijpers8-Oct-10 9:39
MemberHerre Kuijpers8-Oct-10 9:39 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.