Multiple using statements with one block

suggest change

It is possible to use multiple nested using statements without adding 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 can trigger Microsoft Code Analysis rule CA2202 (see this answer for clarification) when one object disposes the other, as when a StreamReader wraps a stream that an outer using also disposes. Independent resources, as in the examples above, do not.

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents