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
C#
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 hereC#
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
usingstatement with an explicit block