← Back to C# Course | Chapter 10: Exception Handling | Lesson 6 of 6

The using Statement

In this page:

  1. The using Statement

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

markup
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());
        }
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.