Skip to content

Using declarations C# 8.0code reductionreadability

Simplify disposable resource management without nesting.

The using statement ensures that IDisposable objects are properly disposed of when they are no longer needed. However, it requires wrapping the code in a block which adds nesting and can make the code harder to read, especially when multiple disposables are involved.

C# 8.0 introduces using declarations which dispose the object at the end of the enclosing scope (typically the method) without requiring an explicit block.

Code ​

csharp
void WriteLog(string message)
{
    using var file = File.OpenWrite("log.txt");
    using var writer = new StreamWriter(file);
    writer.WriteLine(message);
} // both writer and file are disposed here
csharp
void WriteLog(string message)
{
    using (var file = File.OpenWrite("log.txt"))
    {
        using (var writer = new StreamWriter(file))
        {
            writer.WriteLine(message);
        }
    }
}

Notes ​

  • The object is disposed at the end of the enclosing scope, typically when the method returns
  • Particularly useful when you have multiple disposables that would otherwise require deeply nested blocks
  • If you need precise control over when disposal happens, use the traditional using statement with an explicit block
  • The type does not have to implement IDisposable; see pattern-based using C# 8.0 for types that only provide a Dispose method
  • See New lock object C# 13.0 for the disposable lock type that works with both forms of using.

More information ​

Powered by Intracia