Read the syntax
using var creates a local variable whose IDisposable value is disposed at the end of its enclosing scope. This is useful for streams and other resources that need deterministic cleanup.
Disposal closes a resource; it does not create or populate a file. The example creates and fills a temporary file first, then uses finally to delete it even if reading fails.
Syntax
using var reader = File.OpenText("notes.txt");Examples
Disposing a stream reader
A small, runnable example of this syntax.
using System.IO;
string path = Path.GetTempFileName();
try
{
File.WriteAllText(path, "First line");
using var reader = File.OpenText(path);
Console.WriteLine(reader.ReadLine());
}
finally
{
File.Delete(path);
}- A small, runnable example of this syntax.
- using var creates a local variable whose IDisposable value is disposed at the end of its enclosing scope. This is useful for streams and other resources that need deterministic cleanup.
- The program creates a temporary file, writes First line, reads and prints it, disposes the reader at the end of the try scope, and deletes the file in finally.
Best practices
- Use using declarations for disposable resources and keep their scope as small as practical.
- Keep examples small while learning, then combine the idea with a real project.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference