C# and .NET • Modern C# baseline
IDisposable, IAsyncDisposable, and Resource Ownership
Dispose owned resources deterministically and follow the ownership contract of each API.
Garbage collection manages memory but does not promptly release every external resource. IDisposable and IAsyncDisposable represent deterministic cleanup. Use using or await using for owned disposable values; do not dispose a dependency that your component merely borrows unless its contract says you own it.
Key points
- Dispose should be idempotent when practical.
- Async disposal is useful when cleanup itself requires asynchronous I/O.
Example
await using var writer = new StreamWriter("report.txt");
await writer.WriteLineAsync("Report complete");
What to expect
The writer is asynchronously disposed when the scope exits.
Practice exercise
Identify which component owns a stream passed into a method and document whether the method disposes it.
Key idea: Ownership determines who disposes; scope-based cleanup makes that responsibility reliable.