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)
Before
Section titled “Before”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.