typestar

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

  1. The using block disposes the writer at its closing brace, flushing it.
  2. A using var declaration disposes at the end of the enclosing method.
  3. Anything IDisposable — files, connections, timers — fits this shape.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Errors & files, step 27 of 29 in Language basics.

← Previous Next →