using & Dispose in C#
Deterministic cleanup: the file handle closes when the scope ends.
var path = Path.GetTempFileName();
// a using block disposes the writer, flushing it, when the scope ends
using (var writer = new StreamWriter(path))
{
writer.WriteLine("buffered until disposed");
}
// the shorter using declaration disposes at the end of the method
using var reader = new StreamReader(path);
Console.WriteLine(reader.ReadLine());
How it works
- The
usingblock disposes the writer at its closing brace, flushing it. - A
using vardeclaration disposes at the end of the enclosing method. - Anything
IDisposable— files, connections, timers — fits this shape.
Keywords and builtins used here
newusingvar
The run, in numbers
- Lines
- 11
- Characters to type
- 348
- Tokens
- 52
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 35 seconds.
Step 3 of 3 in Errors & files, step 27 of 29 in Language basics.