using statement
Learn automatic dispose with the using statement and using declaration.
The using statement and declaration
The using statement automatically Disposes an IDisposable object at the end of a block. using (var r = new Reader()) { /* ... */ } calls r.Dispose() when the block ends, even on exception.
Since C# 8 the using declaration is shorter: using var r = new Reader(); disposes r when its scope ends. Both forms do the same job.
The classic using statement
The classic form of the using statement uses parens and a block: using (var r = new Reader()) { /* use r */ }. When the block ends (normally or via exception) Dispose is called.
Multiple resources require nested usings. Modern code prefers the using declaration; it is cleaner when no block is needed.
Exercise Use a using declaration with Reader
The Reader class implements IDisposable. In public void Dispose() write Console.WriteLine("Closed");. In Main use using var r = new Reader();.
Show example solution
using var r = new Reader();
Example solution:
using System;
class Reader : IDisposable
{
public void Dispose()
{
Console.WriteLine("Closed");
}
}
class Program
{
static void Main()
{
using var r = new Reader();
}
}
Test yourself
-
When does a using declaration call Dispose?
- When the object is created
- Only at Main exit
- When the GC runs
- When the scope ends
Show answer
When the scope ends — Correct. A using declaration disposes at scope end.
-
Complete the using declaration
using ____ r = new Reader();Show answer
using var r = new Reader(); -
Match the using forms
- using var r;
- Declaration
- using (var r = ...)
- Statement
- Dispose()
- Frees the resource
- IDisposable
- Required interface for using