Cook Computing

Nested Using Statements

August 6, 2004 Written by Charles Cook

Nested using statements can soak up a lot of indentation so Eric Gunnerson has posted a tip on how to code them more succinctly. Taking his example, instead of this:


using (StreamWriter w1 = File.CreateText("W1"))
{
    using (StreamWriter w2 = File.CreateText("W2"))
    {
        // code here
    }
}

you can write this:


using (StreamWriter w1 = File.CreateText("W1"))
using (StreamWriter w2 = File.CreateText("W2"))
{
    // code here
}

The comments are interesting. Michael Teper points out this is just a case of dropping the curly brackets for a one statement code block:


using (StreamWriter w1 = File.CreateText("W1"))
    using (StreamWriter w2 = File.CreateText("W2"))
    {
    // code here
    }
and John Rusk asks why you can't do something like this

using (StreamWriter w1 = File.CreateText("W1"), 
    StreamWriter w2 = File.CreateText("W2"))
{
    // code here
}

which I optimistically tried the first time I came across nested Using statements.

UPDATE: You can of course write:


using (StreamWriter w1 = File.CreateText("W1"), 
    w2 = File.CreateText("W2"))
{
    // code here
}

but this only works because the variables are both of the same type. It doesn't work in the more general case where different types are being declared.