Skip to content

C# Feature - using statements

The using statement wraps an IDisposable resource in a block and guarantees that Dispose() runs when the block exits.

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();
}
using (SqlConnection connection = new(connectionString))
{
connection.Open();
// Execute commands here.
}
  • 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.
  • C# 1 introduced the using statement for deterministic cleanup.