C# Feature - using statements
Overview
Section titled βOverviewβThe using statement wraps an IDisposable resource in a block and guarantees that Dispose() runs when the block exits.
Introduced In
Section titled βIntroduced InβC# 1.0 (2002)
var reader = File.OpenText(path);string text = reader.ReadToEnd();reader.Dispose();using (var reader = File.OpenText(path)){ string text = reader.ReadToEnd();}Annotated Example
Section titled βAnnotated Exampleβusing (SqlConnection connection = new(connectionString)){ connection.Open(); // Execute commands here.}Gotchas & Best Practices
Section titled βGotchas & Best Practicesβ- The classic statement disposes at the end of the block, not the whole method.
- Keep the block narrow when you want disposal to happen as early as possible.
Related Features
Section titled βRelated FeaturesβVersion Notes
Section titled βVersion Notesβ- C# 1 introduced the
usingstatement for deterministic cleanup.