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.