using Statement
Question
Describe a
usingblock. How does it work underneath?
Short interview answer
A
usingstatement ensures that anIDisposableobject is disposed when control leaves its scope. Conceptually, it compiles to atry/finallythat callsDispose.
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.