C# › Memory & Garbage Collection
What is the difference between Dispose and Finalize in C#, and when should each actually be used?
IntermediateAnswer
Dispose (part of IDisposable) provides deterministic, explicit cleanup of unmanaged resources -- you call it yourself (typically via a using statement) as soon as you're done with an object, rather than waiting for garbage collection. Finalize (implemented via a destructor, ~ClassName()) is invoked automatically and non-deterministically by the garbage collector as a last-resort safety net before an object's memory is reclaimed, but finalizers add real overhead to GC (finalizable objects require an extra collection pass), so a class implementing IDisposable should call GC.SuppressFinalize(this) inside Dispose to skip the unnecessary finalizer call once cleanup has already happened deterministically.
public class ResourceHandler : IDisposable {
public void Dispose() {
Console.WriteLine("Dispose called - resources freed.");
GC.SuppressFinalize(this); // skip the now-unnecessary finalizer
}
~ResourceHandler() {
Console.WriteLine("Finalizer called by GC - backup cleanup only.");
}
}
using (var handler = new ResourceHandler()) {
// use the resource
} // Dispose() is called automatically here, at a known, predictable pointReal-world example A database connection wrapper implements IDisposable so the connection is always closed deterministically at the end of a using block, while its finalizer exists purely as a safety net catching the rare case where a caller forgot to dispose it properly.