What is the difference between a finalizer and Dispose?

C# Memory Advanced 3–5 Yrs5+ Yrs Conceptual 1 min read

Quick Answer

Dispose() is deterministic cleanup you call (via using) to release resources now. A finalizer (~ClassName()) is a non-deterministic safety net the GC runs if Dispose was never called — it delays collection by an extra GC cycle and you can't rely on when (or whether) it runs.

Dispose is cleanup you trigger explicitly, normally through a using statement, so resources are freed right away. A finalizer is a fallback that the garbage collector runs if Dispose never happened. The problem with finalizers is they make the object take two GC cycles to collect and you have no control over timing. So the pattern is: implement Dispose, and in it call GC.SuppressFinalize so the finalizer is skipped. I only add a finalizer when I hold a raw OS handle directly, and even then I'd rather use SafeHandle which handles it for me.

  • Objects with a finalizer go on the finalization queue; they survive the first GC, get finalized on a dedicated thread, then are collected on the next GC — twice the cost.
  • Dispose() should call GC.SuppressFinalize(this) so the finalizer is skipped when you cleaned up properly.
  • Only write a finalizer if you directly own an unmanaged resource (a raw handle). Prefer SafeHandle, which has the finalizer built in — then your class never needs one.
  • Finalizers can't safely touch other managed objects (they may already be collected).