skip to content

In C# 8 and later, when does a using declaration such as using var connection = Open(); dispose, and in what order do several dispose?

level: middleimportance: must knowfreq 65%

answer

  1. no braces, but still a scope
  2. the enclosing block's closing brace
  3. nested try/finally blocks
  4. last declared, first disposed

basics

~20 s

A using declaration disposes its variable when the enclosing block ends, not at the next line. Several declarations in one block dispose in reverse order of declaration, because the compiler nests one try/finally per declaration.

solid answer

~50 s

`using var connection = Open();` (C# 8) has no block of its own: the variable is disposed when control leaves the scope it is declared in, which is the method body, an `if` or loop body, or a pair of bare braces. The compiler treats the rest of that block as the body of a `try` and puts `Dispose()` in its `finally`, so each later declaration is nested inside the earlier ones and disposal runs in reverse: last declared, first disposed. Because the finallys are nested, an earlier resource is still disposed even if a later `Dispose()` throws, but the exception thrown from that `Dispose()` replaces any exception already in flight. The cost of the convenience is lifetime: a declaration at the top of a long method holds its resource until the method returns. The compiler also rejects one directly in a `switch` section (CS8647) and a `goto` across one (CS8648, CS8649).

code

csharp · 19 lines
csharp
Generate();

static void Generate()
{
    using var file = new Resource("file");
    using var connection = new Resource("connection");
    {
        using var temp = new Resource("temp");
        Console.WriteLine("inner block ends");
    }
    Console.WriteLine("method ends");
}

sealed class Resource : IDisposable
{
    private readonly string _name;
    public Resource(string name) { _name = name; Console.WriteLine($"open {name}"); }
    public void Dispose() => Console.WriteLine($"Dispose {_name}");
}

go deeper

for a junior

Recall that a using declaration lasts until the end of the enclosing block and that several of them dispose last-declared first.

for a middle

Explain the lowering into nested try/finally blocks and how it produces the reverse order, plus the CS8647 switch-section rule and the returned-disposed-object trap.

for a senior

Spot a declaration that holds a connection or file far longer than needed, and explain why an exception from Dispose masks the original failure.

for a principal

Set a style expectation for when the flat declaration is fine and when a narrower statement or block is required for scarce resources.

## Using declarations in one paragraph C# 8 added the **using declaration**: the keyword `using` in front of a local variable declaration, with no parentheses and no block. ```csharp using var file = new FileStream(path, FileMode.Create); using var connection = OpenConnection(); ``` It means the same thing as a `using` statement whose block is *everything from this line to the end of the enclosing scope*. The variable is read-only, its type must be disposable, and `Dispose()` is guaranteed on every exit from that scope. ## When the object is disposed The "enclosing scope" is the nearest pair of braces around the declaration: - in a **method body**, disposal happens when the method returns or throws; - in an **`if` block, loop body or bare `{ }` block**, it happens when that block ends, so a declaration inside a `foreach` body disposes once per iteration; - in a **lambda or local function body**, it happens when that body finishes. That makes the lifetime longer than many readers expect. In a report generator, this keeps the database connection open while the whole file is formatted: ```csharp void Generate(string path) { using var connection = OpenConnection(); var rows = LoadRows(connection); // connection needed only here using var file = new FileStream(path, FileMode.Create); WriteReport(file, rows); // slow; connection still open } // file disposed, then connection ``` The fix is to give the connection a smaller scope: a `using` statement around `LoadRows`, or a bare `{ }` block around those two lines. One more consequence: `return connection;` from a method that declared `using var connection` compiles, but the caller receives an object that was disposed on the way out. ## The order, and why it is reversed The compiler lowers each declaration to a `try`/`finally` whose `try` body is the rest of the block. Two declarations therefore become nested blocks: ```csharp var file = new FileStream(path, FileMode.Create); try { var connection = OpenConnection(); try { /* rest of the block */ } finally { if (connection != null) connection.Dispose(); } } finally { if (file != null) file.Dispose(); } ``` From that shape: 1. The **last declared** resource is disposed **first**, because its `finally` is innermost. 2. A resource declared later may depend on an earlier one (a writer over a stream), and the reverse order disposes the dependent object before the thing it depends on. 3. If the second constructor throws, the first resource is already inside its `try`, so it is still disposed. The same reverse order applies to several variables in one `using` statement, `using (FileStream a = ..., b = ...)`. ## When Dispose itself throws Nested `finally` blocks have a well-defined but unwelcome interaction with exceptions: | Situation | What runs | What the caller sees | |---|---|---| | Body throws, every `Dispose()` succeeds | All disposals, innermost first | The body's exception | | Body completes, an inner `Dispose()` throws | The outer disposals still run | The `Dispose()` exception | | Body throws, an inner `Dispose()` also throws | The outer disposals still run | The `Dispose()` exception; the original is lost | The last row is why the .NET design guidelines say to avoid throwing from `Dispose(bool)` except in critical situations: an exception from cleanup hides the failure that actually caused the problem. ## Rules the compiler enforces - **CS8647**, "A using variable cannot be used directly within a switch section (consider using braces)." Wrap the section's statements in braces to give the declaration a block. - **CS8648** and **CS8649**: a `goto` cannot jump forward past a using declaration or back to a point before one in the same block, since either would skip or repeat the acquisition. - **CS1656**: the variable cannot be reassigned, exactly as in a `using` statement. - **CS9229**: no modifiers such as `static` or `readonly` on the declaration. ## Choosing between the two forms - Use a **declaration** when the resource is needed until the end of the block anyway, which is common in short methods, and enjoy the flatter code. - Use a **statement** (or a bare block) when the resource should be released before the method finishes, for example a connection, a lock-like handle or a file another step will reopen.

  • Why does `case 1: using var r = Open(); break;` fail to compile, and what is the fix?
    A `switch` section is not a block, so the compiler cannot give the declaration a clear scope and reports CS8647, "A using variable cannot be used directly within a switch section (consider using braces)." Wrapping the section's statements in braces, `case 1: { using var r = Open(); ... break; }`, makes the declaration dispose at that closing brace.
  • A method declares `using var connection = Open();` and then `return connection;`. What does the caller get?
    An object that has already been disposed. The `return` value is computed, the `finally` from the declaration runs as control leaves the method, and only then does the caller receive the reference. Its next call will typically throw `ObjectDisposedException`. A method that hands a disposable to its caller must not put it in a `using`.
  • If an inner Dispose() throws while the body's exception is already propagating, which exception reaches the catch?
    The one from `Dispose()`. An exception thrown in a `finally` replaces the exception in flight, so the original failure is lost unless something logged it first. The outer `finally` blocks still run, so earlier resources are disposed. This is why `Dispose` implementations should avoid throwing.

  • A using declaration disposes right after the next statement
  • Several using declarations dispose in the order they were declared
  • If one Dispose throws, the resources declared before it are never disposed
  • A using declaration can be placed directly in a switch case section
  • Returning a using variable from a method gives the caller a live object