Things I Didn’t Know – Stacking Your Using Statements

One of the things that I love about the .NET framework is that I am constantly learning new things about it, finding new jewels that save me time, and just some really interesting bits.  This latest item I found falls into the “interesting bits” category.

Probably like many of you, I’ve written a number of console applications to do some tasks quickly and with little fanfare.  Usually these tasks are one-time tasks, and the console application is almost a throw-away project once I’m done with it.  Because of this, I usually attempt to get things done quickly and sometimes my code isn’t the neatest – shocking, I know!

Well, for this one task, I had to read information from a CSV file, write a status to a TXT file and also write some updates to our data layer.  These tasks involve the use of IDisposable objects; and as a result, I usually wrap these in a using block.

Here’s what my code usually looks like:

   1: using (StreamWriter sw = new StreamWriter(statusFile, true))
   2: {
   3:     using (StreamReader sr = new StreamReader(filename, Encoding.Default))
   4:     {
   5:         using (CsvReader csv = new CsvReader(sr, true))
   6:         {
   7:             //some work is done here
   8:         }
   9:     }
  10: }

 

So not too bad, but most of the ‘real’ code in my project tends to be in the middle of the IDE due to all of the indenting.

I can stack my using statements, instead, on top of each other, and have them all be contained with a single block, like so:

   1: using (StreamWriter sw = new StreamWriter(statusFile, true))
   2: using (StreamReader sr = new StreamReader(filename, Encoding.Default))
   3: using (CsvReader csv = new CsvReader(sr, true))
   4: {
   5:     //some work is done here
   6: }

 

Much cleaner, much more condense, a little easier to read (IMHO) and it saves a few lines.  It’s nice when you find out something new in a language you’ve been using for years.  I’m a little embarrassed that I didn’t know you could do this, but I’m glad I know now.

posted @ Friday, April 15, 2011 4:25 PM
Print

Comments on this entry:

# re: Things I Didn’t Know – Stacking Your Using Statements

Left by Keith Nicholas at 4/18/2011 8:12 PM
Gravatar
err, this is the same "stacking" as with if statements, while statements etc....

unless you open a block ( ' { ' ) the if/while/using/lock etc will apply to the next statement

eg

if(x)
if(y)
if(z)
{
//blah
}

Your comment:



(not displayed)

 
 
 
 
 

Live Comment Preview:

 
«August»
SunMonTueWedThuFriSat
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456