0Pricing
C# Academy · Lesson

IDisposable, using statement

Implement IDisposable, use the using statement for deterministic cleanup, and contrast with manual try/finally. C# 6 only.

IDisposable, using statement is a free C# Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why IDisposable + using

Goal: Free resources deterministically.

  • Implement IDisposable
  • Use the using statement (C# 6)
  • Compare with try/finally
  • Keep cleanup small and safe

Implement IDisposable

Implement IDisposable.Dispose to release resources (files, sockets, handles). Keep it idempotent.

using System;

// Simple disposable that tracks whether it was cleaned up
public sealed class FakeConnection : IDisposable
{
  public bool IsOpen { get; private set; }

  public FakeConnection()
  {
    IsOpen = true;
    Console.WriteLine("Open");
  }

  public void Dispose()
  {
    if (IsOpen)
    {
      IsOpen = false;
      Console.WriteLine("Close");
    }
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    FakeConnection c = new FakeConnection();
    c.Dispose(); // manual cleanup
  }
}

try/finally pattern

try/finally guarantees cleanup but is verbose and easy to forget. The using statement is a shorthand.

using System;

public sealed class FakeConnection : IDisposable
{
  public void Dispose() { Console.WriteLine("Dispose called"); }
  public void Send(string msg) { Console.WriteLine("Send: " + msg); }
}

public class Program
{
  public static void Main(string[] args)
  {
    // Manual try/finally
    FakeConnection a = null;
    try
    {
      a = new FakeConnection();
      a.Send("A");
      throw new Exception("boom");
    }
    finally
    {
      if (a != null) a.Dispose(); // runs even on exception
    }

    // unreachable due to thrown exception in this demo
  }
}

using statement demo

The using statement wraps a hidden try/finally; Dispose is called when the block ends.

using System;

public sealed class FakeConnection : IDisposable
{
  public void Dispose() { Console.WriteLine("Dispose called"); }
  public void Work() { Console.WriteLine("Working"); }
}

public class Program
{
  public static void Main(string[] args)
  {
    try
    {
      using (FakeConnection c = new FakeConnection())
      {
        c.Work();
        throw new InvalidOperationException("oops");
      } // Dispose runs here automatically
    }
    catch (Exception)
    {
      Console.WriteLine("Handled");
    }
  }
}

I/O with using

Most I/O types implement IDisposable. Use using so handles are closed promptly.

using System;
using System.IO;

public class Program
{
  public static void Main(string[] args)
  {
    // Create a small temp file then read it
    string path = "demo.txt";
    File.WriteAllText(path, "hello");

    using (StreamReader r = new StreamReader(path))
    {
      string text = r.ReadToEnd();
      Console.WriteLine(text);
    } // r.Dispose() closes the file handle
  }
}

Using tips & pitfalls

Tips:

  • Prefer using over manual Dispose calls.
  • Keep Dispose small and safe (no throws if possible).
  • Do not use objects after they are disposed.
  • For multiple resources, nest using blocks to control order.

using statement guarantee

Quick check: What does the using statement guarantee for an IDisposable object?

Recap

Recap: Implement IDisposable for resources and wrap usage in a using block to ensure cleanup via a hidden try/finally in C# 6.

Frequently asked questions

Is the “IDisposable, using statement” lesson free?

Yes — the full text of “IDisposable, using statement” is free to read here on the web, and the C# Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “IDisposable, using statement”?

Implement IDisposable, use the using statement for deterministic cleanup, and contrast with manual try/finally. C# 6 only. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “IDisposable, using statement” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. try/catch/finally, throw new vs rethrow
  2. Custom exceptions; error design
  3. IDisposable, using statement
← Back to C# Academy