Glossary / using declarations

using declarations

A using declaration ensures an IDisposable resource is disposed at the end of the enclosing scope, including when control exits through exceptions or returns. It is a concise alternative to a using statement block and provides deterministic cleanup for resources such as streams, transactions, and handles.

Scope and disposal order

using var reader = File.OpenText(path);
string? line = reader.ReadLine();

The resource remains alive until the end of the containing scope, not merely the next statement. Multiple using declarations dispose in reverse order of declaration, similar to nested scopes. A using declaration is lowered to try/finally semantics; Dispose() is called even when work throws. If a variable is nullable or assignment is conditional, disposal behavior follows the resource expression and compiler lowering.

await using works with IAsyncDisposable and awaits DisposeAsync at scope exit. Cleanup exceptions can replace an in-flight exception depending on how disposal behaves; design disposal to be reliable and understand exception aggregation policies. using var does not make an object immutable or prevent aliases from using it after disposal.

Engineering guidance

Keep resource lifetime as short as practical; use a block when a shorter scope improves ownership clarity. Do not return a resource from a scope that will dispose it. Avoid capturing disposed resources in callbacks. Test cleanup on success, early return, and failure.

Interview questions

  1. When is a using declaration disposed? At the end of its containing scope.
  2. What is disposal order for multiple declarations? Reverse declaration order.
  3. What does await using do? Awaits DisposeAsync on an IAsyncDisposable resource.
  4. Does using prevent later alias access? No; aliases can exist but refer to a disposed resource.
  5. Why choose a using statement block? To make a narrower resource lifetime explicit.

References