Help me – I’m a user.

I need help. I’m a user – I admit it. I love using the using statement in C# (I’m not talking about the one that’s equivalent to the #include statement). Imagine my surprise that some people haven’t heard of this wonderful, wonderful keyword.

So what does it actually do? Well, you can think of it as automatically calling Dispose on a disposable object. Effectively, it translates into a try/finally block where Dispose is called automatically in the finally section. So:

using (SqlConnection conn = new SqlConnection())
 // Do something...

translates into

SqlConnection conn = null;
  conn = new SqlConnection();
  // Do something..
  if (conn != null && conn is IDisposable)

It’s perfectly possible to nest using blocks, and the compiler will ensure that Dispose is called in the correct fashion. So, if a class has a Dispose method, you should really consider wrapping it in a using(…) block.

Warning – If the class you are referencing in the using statement doesn’t implement IDisposable then you can’t do this.

Now, did you know that you can alias namespaces in a using statement? It’s true – if you don’t want to put in that StreamWriter is in the System.IO namespace all over your code and you are in the midst of classname conflicts, it’s a simple matter to put something like the following in your code:

using io = System.IO;

Then, elsewhere in your code you can use:

using (io.StreamWriter sw = new io.StreamWriter(@"c:\dev.txt"))

Note the “clever” use of the two different using types.


2 thoughts on “Help me – I’m a user.

  1. peteohanlon

    nirandas, rather than putting the try/catch around the using statement, you can actually put it inside. Even if you throw an exception in the catch block, the Dispose will still be called because it’s part of the finally block.

Leave a Reply

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

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

Facebook photo

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

Connecting to %s