Using ‘using’

Using classes (and structures for that matter) that implement IDisposable has one implication: when you’re done using it, you should ASAP call it’s Dispose() method.

Like in the example:

Pies item1 = new Pies("Pies 1");

Console.WriteLine("Accessing {0}", item1.Name);

item1.Dispose();

To make life easier, and not have to remember to call this method directly you can alternatively use some ‘syntactic sugar’ in form of the ‘using’ keyword, and rewrite this example to (more or less, as we’ll se in just a second) equivalent code:

using(Pies item1 = new Pies("Pies 1"))

{

    Console.WriteLine("Accessing {0}",item1.Name);

}

This approach has quite a few advantages: you are freed from calling Dispose() explicitly (it get’s called after last line of code within ‘{‘ and ‘}’ ends executing), it’s more readable, and it limits the visibility of item1, what may be desirable in some cases (for example, you will not be able to call item1 after it’s disposed of, which might cause some nasty, run-time errors).

As I said, ‘using’ keyword, is just a syntactic sugar. Beneath it, is code looking like this (via Reflector):

Pies item1;

bool CS$4$0000;

item1 = new Pies("Pies 1");

l_000C:

try

{

    Console.WriteLine("Accessing {0}", item1.Name);

    goto Label_0031;

}

finally

{

Label_0021:

    if ((item1 == null) != null)

    {

        goto Label_0030;

    }

    item1.Dispose();

Label_0030:;

}

l_0031:

    return;

It wraps, the code we put within ‘using’ range with try/finally just to make sure that Dispose() gets called even if something goes wrong.

You can embed ‘using’ statements, one, within another like this:

using (Pies item1 = new Pies("Pies 1"))

{

    using (Pies item2 = new Pies("Pies 2"))

    {

        Console.WriteLine("Accessing {0}", item1.Name);

        Console.WriteLine("Accessing {0}", item2.Name);

    }

}

or in a shorter form:

using (Pies item1 = new Pies("Pies 1"))

using (Pies item2 = new Pies("Pies 2"))

{

    Console.WriteLine("Accessing {0}", item1.Name);

    Console.WriteLine("Accessing {0}", item2.Name);

}

What I didn’t know was, that when all variables you’re ‘using’ are of the same type (like in the example: both item1 and item2 are of type Pies) you can shorter it even further to this form:

using (Pies item1 = new Pies("Pies 1"), item2 = new Pies("Pies 2"))

{

    Console.WriteLine("Accessing {0}", item1.Name);

    Console.WriteLine("Accessing {0}", item2.Name);

}

All three snippets result in identical IL. I’d most often opt for the second solution. It’s concise, readable, and enable me to use variables of more than one type (like StreamReaded/StreamWriter).

Technorati Tags: , ,