Using Using For Clean Code

I’ve been using files for a long time and at times I stumble across this kind of code before:

public void WorkFileMagic(string fileName)
{
// Work some validation checks, etc.
System.IO.StreamReader reader = new System.IO.StreamReader(fileName);
string data = reader.ReadToEnd();
// Work with the data.
reader.Close();
}

Let’s fix this code up a bit:

public void WorkFileMagic(string fileName)
{
// Work some validation checks, etc.
System.IO.StreamReader reader = null;
try
{
reader = System.IO.File.OpenText(fileName);
string data = reader.ReadToEnd();
// Work with the data.
}
finally
{
if (reader != null)
{
reader.Close();
}
}
}

So what else is there to do? How would you like this?

public void WorkFileMagic(string fileName)
{
// Work some validation checks, etc.
using (System.IO.StreamReader reader = System.IO.File.OpenText(fileName))
{
string data = reader.ReadToEnd();
// Work with the data.
}
}

So what I wanted to talk about was C#’s using statement.
What it does is take the variable that sits between the parenthesis and disposes of it (using IDisposable.Dispose) at the end of the code structure, whether an exception has been thrown or not. The variable’s type must implement IDisposable. What it means in the third code segment is that the file is closed for you and you don’t have to take care of it.
I’ve been using using for things like files, GDI+ objects, etc. It’s quite useful.
using isn’t part of the IL, so the second and third code segments come out very close to each other in the final IL.

More about using, here and here.

Advertisements

One thought on “Using Using For Clean Code

  1. It’s fine when you have a single object to be disposed. But once you get to accessing a database, where you have at least two (the connection and the data reader), possibly a lot more (multiple queries) using gets old pretty quick and you’ll go back to using try/catch/finally.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s