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.

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
  }
}

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