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

The using Statement

The using statement makes sure something is cleaned up as soon as you finish with it, like automatically closing the fridge door. It is used for things like files that must be released.

In this page:

  1. The using Statement
Syntax
csharp
using (ResourceType resource = new ResourceType())
{
    // use resource; Dispose() is called at the end
}

using var resource = new ResourceType();   // C# 8 declaration form

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());
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using a type that does not implement IDisposable in a using statement, which is a compile error.
  2. Using the disposed object after the using block ends, which throws ObjectDisposedException.
  3. Forgetting using for streams or connections, so they stay open.
Chapter Summary
  • try, catch, and finally handle errors and clean up.
  • Exception types, custom exceptions, throw, and exception filters (when) control what is thrown and caught.
  • The using statement releases resources automatically.
🔒

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.