The using Statement
In this page:
The using Statement
The using statement ensures an IDisposable object's Dispose() method is called automatically once the block ends, even if an exception occurs — commonly used for files, streams, and database connections. It's syntactic sugar over a try/finally that calls Dispose(). This prevents resource leaks from forgetting manual cleanup.
Note: Anything implementing IDisposable, like StreamReader or StreamWriter, should be wrapped in using.
Example: The using Statement
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = "notes.txt";
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine("Hello from a using block");
}
using (StreamReader reader = new StreamReader(path))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: