Skip to content

using Statement

Question

Describe a using block. How does it work underneath?

Short interview answer

A using statement ensures that an IDisposable object is disposed when control leaves its scope. Conceptually, it compiles to a try/finally that calls Dispose.

Detailed answer

Use using when the current scope owns a disposable resource:

using var stream = File.OpenRead(path);
var document = JsonDocument.Parse(stream);

When execution leaves the scope—whether normally or because Parse throws—the compiler-generated cleanup path calls stream.Dispose(). Conceptually it is a try/finally; it is not a hint to the garbage collector. That matters for files, database connections, and native handles, where waiting for eventual collection can exhaust a scarce resource. Use await using when the resource implements IAsyncDisposable and cleanup itself is asynchronous.

Sources