Skip to content

C# Feature – using (statements & declarations)

using ensures IDisposable resources are disposed. C# 8 added using declarations and using var.

C# 1 (statement), C# 8 (declaration)

var fs = File.OpenRead(path);
// remember to dispose later
using var fs = File.OpenRead(path); // disposed at end of scope
// Classic statement
using (var stream = File.OpenRead(path))
{
// use stream
}
// Declaration form (C# 8+)
using var stream2 = File.OpenRead(path);
  • using declaration disposes at end of scope, not immediately.
  • Prefer await using for IAsyncDisposable.