Back to results for “Garbage Collection”
C# › Memory & Garbage Collection

How does the IDisposable pattern and the 'using' statement help manage UNMANAGED resources that the garbage collector doesn't automatically clean up?

Intermediate

Answer

The garbage collector only manages MANAGED memory — it doesn't know how to release unmanaged resources like file handles, database connections, or OS handles. IDisposable's Dispose() method provides a deterministic way to release those resources explicitly, and 'using' guarantees Dispose() is called automatically when the object goes out of scope, even if an exception occurs.
public class FileWrapper : IDisposable {
  private readonly FileStream _stream;
  public FileWrapper(string path) { _stream = File.OpenRead(path); }
  public void Dispose() => _stream.Dispose(); // releases the unmanaged file handle
}
using (var wrapper = new FileWrapper("data.txt")) { /* ... */ } // Dispose() guaranteed to run
Real-world example Ensuring a database connection, file handle, or network socket is promptly released rather than waiting for the GC's unpredictable timing.

Common follow-ups: What happens to an unmanaged resource if you forget to implement IDisposable and never explicitly release it?