C# Language Multiple using statements with one block


Example

It is possible to use multiple nested using statements without added multiple levels of nested braces. For example:

using (var input = File.OpenRead("input.txt"))
{
    using (var output = File.OpenWrite("output.txt"))
    {
        input.CopyTo(output);
    } // output is disposed here
} // input is disposed here

An alternative is to write:

using (var input = File.OpenRead("input.txt"))
using (var output = File.OpenWrite("output.txt"))
{
    input.CopyTo(output);
} // output and then input are disposed here

Which is exactly equivalent to the first example.

Note: Nested using statements might trigger Microsoft Code Analysis rule CS2002 (see this answer for clarification) and generate a warning. As explained in the linked answer, it is generally safe to nest using statements.

When the types within the using statement are of the same type you can comma-delimit them and specify the type only once (though this is uncommon):

using (FileStream file = File.Open("MyFile.txt"), file2 = File.Open("MyFile2.txt"))
{
}

This can also be used when the types have a shared hierarchy:

using (Stream file = File.Open("MyFile.txt"), data = new MemoryStream())
{
}

The var keyword cannot be used in the above example. A compilation error would occur. Even the comma separated declaration won't work when the declared variables have types from different hierarchies.