C# Feature – using (statements & declarations)
Overview
Section titled “Overview”using
ensures IDisposable resources are disposed. C# 8 added using declarations and using var.
Introduced In
Section titled “Introduced In”C# 1 (statement), C# 8 (declaration)
Before
Section titled “Before”var fs = File.OpenRead(path);// remember to dispose later
using var fs = File.OpenRead(path); // disposed at end of scope
Annotated Example
Section titled “Annotated Example”// Classic statementusing (var stream = File.OpenRead(path)){ // use stream}
// Declaration form (C# 8+)using var stream2 = File.OpenRead(path);
Gotchas & Best Practices
Section titled “Gotchas & Best Practices”- using declaration disposes at end of scope, not immediately.
- Prefer await using for IAsyncDisposable.