Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Classes and Object-Oriented Concepts

The IDisposable pattern

Reference for IDisposable in C#: releasing files, sockets and other resources with Dispose, using statements and declarations, the full pattern and IAsyncDisposable.

The garbage collector reclaims memory, but it knows nothing about files, sockets, database connections, locks or native handles. A type that owns such a resource implements IDisposable, which has a single method, Dispose(). Calling it releases the resource immediately and deterministically, instead of whenever the garbage collector happens to run.

You rarely call Dispose() by hand. The using statement and the using declaration call it for you, even when an exception is thrown. The rule of thumb: if you create an object whose type implements IDisposable, you are responsible for disposing it (unless something else explicitly takes ownership).

C#
using var reader = new StreamReader("data.txt");
string? line = reader.ReadLine();
// reader.Dispose() runs automatically at the end of the enclosing scope

Try it

C# using statement and using declaration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# The full pattern and IAsyncDisposable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public interface IDisposable
{
    void Dispose();
}

public interface IAsyncDisposable
{
    ValueTask DisposeAsync();
}

using (expression) statement
using var name = expression;
await using var name = expression;
Part Description
Dispose() Releases the resources the object owns. Returns nothing.
using (...) { } Disposes the object when the block ends, normally or by exception. Several using lines can be stacked.
using var x = ...; Declaration form (C# 8). The object is disposed at the end of the enclosing scope, in reverse order of declaration.
await using Calls DisposeAsync() and awaits it. Use it for types that implement IAsyncDisposable.

Errors: after disposal, members of the object usually throw ObjectDisposedException. Dispose() itself should not throw; it must be safe to call more than once.

Usage notes

  • Make Dispose() idempotent. Callers and containers may dispose an object twice. Keep a _disposed flag and return early on the second call.
  • A sealed class that only owns managed disposable fields needs just the simple form: dispose the fields in Dispose(). You do not need a finalizer and you do not need GC.SuppressFinalize.
  • The protected Dispose(bool disposing) pattern is for unsealed base classes that may be derived from, or that own unmanaged resources directly. Dispose() calls Dispose(true) and GC.SuppressFinalize(this). A finalizer, if you have one, calls Dispose(false). See Finalizers.
  • Prefer SafeHandle over raw IntPtr for native handles. It brings its own finalizer, so your class usually needs none.
  • A using declaration disposes at the end of the scope, which may be later than you expect. Use the block form when you want to release something early.
  • Dispose in reverse order of creation when objects depend on each other. Stacked using statements already do this.
  • A using variable is read-only. You cannot assign a new object to it inside the block.
  • Dispose does not make the object null and does not free managed memory. It only releases the extra resources.
  • Do not dispose what you do not own. An HttpClient from a factory, a Stream passed in by a caller that keeps using it, or a shared logger belong to someone else.
  • Async code: if a type offers both interfaces, prefer await using in async methods so no thread blocks while waiting for the flush or close.
  • Exceptions in Dispose replace the exception that was already in flight in a using block, so keep cleanup code tiny and defensive.