Using declarations in C# 8.0 keep the same deterministic disposal semantics as using (...) { }, but with less visual noise. The resource is disposed at the end of the enclosing scope.
Why it matters
- Reduces indentation and keeps business logic flatter.
- Preserves safe deterministic disposal for
IDisposableresources. - Improves readability in methods that open several resources.
Cautions
Lifetime now extends to the end of the current scope, not the end of a nested block. Keep scopes tight so expensive resources are not held longer than necessary.
Traditional using block vs using declaration
Using declarations keep disposal guarantees while reducing block nesting.
Valid since C# 8.0
Without var
using System;
public sealed class ScopeLogger : IDisposable
{
private readonly string _name;
public ScopeLogger(string name)
{
_name = name;
Console.WriteLine("Opened " + _name);
}
public void Dispose()
{
Console.WriteLine("Disposed " + _name);
}
}
public static class Program
{
public static void Main()
{
using (var logger = new ScopeLogger("outer"))
{
Console.WriteLine("Working inside using block");
}
}
}
With var
using System;
public sealed class ScopeLogger : IDisposable
{
private readonly string _name;
public ScopeLogger(string name)
{
_name = name;
Console.WriteLine("Opened " + _name);
}
public void Dispose()
{
Console.WriteLine("Disposed " + _name);
}
}
public static class Program
{
public static void Main()
{
using var logger = new ScopeLogger("outer");
Console.WriteLine("Working with flatter structure");
}
}
Multiple resources in one scope
Each using declaration is disposed automatically at the end of the current scope.
Valid since C# 8.0
using System;
public sealed class ScopeLogger : IDisposable
{
private readonly string _name;
public ScopeLogger(string name)
{
_name = name;
Console.WriteLine("Opened " + _name);
}
public void Dispose()
{
Console.WriteLine("Disposed " + _name);
}
}
public static class Program
{
public static void Main()
{
using var first = new ScopeLogger("first");
using var second = new ScopeLogger("second");
Console.WriteLine("Do work with two resources");
}
}