In C#, what does a using statement do with the object it declares, and is Dispose still called when the block throws?
answer
- a compiler rewrite, not a runtime feature
- try with a finally
- null check before the call
- return, break and throw all leave
basics
~20 sA using statement calls Dispose on its resource when control leaves the block, however it leaves: normal completion, return, break or an exception. The compiler lowers it to try/finally, with a null check for reference types.
solid answer
~50 s`using (var report = new FileStream(path, FileMode.Create)) { ... }` is shorthand that the compiler expands into a `try`/`finally`: the resource is acquired before the `try`, the block becomes the `try` body, and the `finally` calls `Dispose()`. Because it is a `finally`, `Dispose` runs whether the block completes, returns, breaks out or throws, and the exception then keeps propagating to whoever catches it. For a reference type or a nullable value type the `finally` checks for null first, so a null resource is skipped instead of causing a `NullReferenceException`. The variable is read-only inside the block (assigning to it is CS1656), and the type must implement `IDisposable` (CS1674), with one exception: a `ref struct` that has an accessible parameterless `void Dispose()`. `using` catches nothing, and if the constructor throws there is no object to dispose.
code
csharp · 22 linestry
{
using (var report = new Resource("report.tmp"))
{
Console.WriteLine("writing rows");
throw new InvalidOperationException("row 3 is malformed");
}
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"caught: {ex.Message}");
}
using (Resource? none = null)
{
Console.WriteLine("null resource: no Dispose call, no exception");
}
sealed class Resource(string name) : IDisposable
{
public void Dispose() => Console.WriteLine($"Dispose {name}");
}go deeper
Recall that using calls Dispose on every exit from the block, including exceptions and early returns, and that the exception still propagates afterwards.
Explain the try/finally lowering, the null check for reference types, the read-only variable (CS1656) and why the type must implement IDisposable (CS1674).
Point out what using cannot guard: a constructor that throws before assignment, nested constructors in one acquisition, and the expression form whose variable outlives the dispose.
Treat using as the default shape for every locally created disposable, and back that expectation with analyzer rules rather than review comments alone.
## What the using statement is for Many .NET types hold something the garbage collector does not manage well on its own schedule: an open file, a socket, a database connection, a lock on a shared resource. Such types implement **`IDisposable`**, whose single method `Dispose()` releases the resource *now*, deterministically. The **`using` statement** is the C# construct that guarantees `Dispose()` is called when a piece of code is finished with the object. Take a report generator that writes its output to a temporary file: ```csharp using (var report = new FileStream(path, FileMode.Create)) { WriteHeader(report); WriteRows(report); // may throw } // report.Dispose() has run here, on every path ``` ## What the compiler turns it into `using` is not a runtime feature; the C# compiler rewrites it. For a class type the expansion is, in effect: ```csharp { FileStream report = new FileStream(path, FileMode.Create); try { WriteHeader(report); WriteRows(report); } finally { if (report != null) ((IDisposable)report).Dispose(); } } ``` Three details follow from that shape: 1. The resource is acquired **before** the `try`. If the `FileStream` constructor throws, there is no object yet, so there is nothing to dispose and the `finally` never runs. 2. The body is the `try` block, so **every way out** passes through the `finally`. 3. The extra braces limit the variable's scope to the statement. ## Every exit runs Dispose The `finally` makes the guarantee, so `Dispose()` runs when the block: - reaches its closing brace normally; - executes `return`, even with a value computed from the resource; - leaves through `break`, `continue` or `goto` to a label outside; - throws an exception, or calls something that throws. In the exception case `Dispose()` runs **and then the exception keeps propagating**: `using` does not catch or swallow anything. If you want to handle the failure, put a `try`/`catch` around the `using` or inside it. A failure that tears the process down without unwinding the stack is beyond any `finally`; that edge belongs with try, catch and finally themselves. ## The null check and value types The compiler adapts the `finally` to the resource's type. The Roslyn lowering (`LocalRewriter_UsingStatement.cs`) quotes the C# specification for these expansions: | Resource type | What the `finally` does | |---|---| | Class or interface | `if (r != null) r.Dispose();` | | Non-nullable struct | Calls `Dispose()` directly, through a constrained call that avoids boxing | | Nullable struct (`S?`) | `if (r.HasValue) r.GetValueOrDefault().Dispose();` | | `dynamic` | Converts to `IDisposable` before the `try`, then null-checks | So `using (Resource? none = null) { ... }` simply runs the block; there is no `NullReferenceException`. That is useful when a resource is optional. ## Rules the compiler enforces - **The type must be disposable.** A class without `IDisposable` is rejected with CS1674, "'NotDisposable': type used in a using statement must implement 'System.IDisposable'.", even if it happens to have a public `Dispose()` method. Since C# 8 a `ref struct` with an accessible, parameterless `void Dispose()` is accepted by pattern, because a ref struct could not implement interfaces before C# 13. - **The variable is read-only.** `report = other;` inside the block is CS1656, "Cannot assign to 'report' because it is a 'using variable'". Passing it as `ref` or `out` is also an error. - **Several resources of one type** can share a statement, `using (FileStream a = ..., b = ...)`, and are disposed in reverse order of declaration. - **The expression form** `using (existing) { ... }` is legal: the compiler copies the value into a hidden local and disposes that. Assigning a new object to `existing` inside the block draws warning CS0728, because the original object is the one that gets disposed and the new one leaks. ## What using does not do - It does not free the object's memory; the garbage collector still owns memory. `Dispose()` releases the *resource* (the file handle), not the managed object. - It does not make the variable unusable afterwards in the expression form: the reference may still be in scope after the statement, already disposed, and calling into it typically throws `ObjectDisposedException`, which is why declaring the variable in the statement is preferred. - It does not replace error handling: a `using` with no `catch` around it lets the exception escape after cleanup, which is usually exactly right.
- Is a using statement the same as calling Dispose() on the last line of the block?No. A `Dispose()` call on the last line only runs if every line before it completes. An exception, an early `return` or a `break` skips it and the file stays open until finalization, if that ever happens. `using` puts the call in a `finally`, so it runs on all of those paths.
- Why can `using (var w = new StreamWriter(new FileStream(path, FileMode.Create)))` leak the FileStream?Only the outer object is guarded. If the `StreamWriter` constructor throws after the `FileStream` was created, no variable holds the stream and no `finally` disposes it, so the file handle waits for finalization. The CA2000 documentation calls out this nested-constructor case. Two separate `using` statements guard each resource as soon as it exists.
- What happens with `var r = Open(); using (r) { r = Open(); }`?It compiles with warning CS0728. The expression form disposes the value `r` held when the statement began, so the first object is disposed and the second, assigned inside the block, is never disposed by this statement. Declaring the variable in the `using` makes it read-only and turns the reassignment into error CS1656.
- using catches the exception, so the caller never sees it
- Dispose is skipped when the block exits through an exception
- using frees the object's memory as soon as the block ends
- Any class with a public Dispose method can be used in a using statement
- A null resource in a using statement throws NullReferenceException