C# Interview Question #75

What is the difference between Dispose and a finalizer?

Memory Management & Modern C# Mid-Level Intermediate

Quick Interview Answer

Dispose provides deterministic cleanup and is called explicitly, usually through a using statement or declaration.

Detailed Explanation

Dispose provides deterministic cleanup and is called explicitly, usually through a using statement or declaration.

A finalizer is invoked by the garbage collector before reclaiming an object that has a finalizer. Its execution time is nondeterministic and finalizable objects impose additional GC overhead.

Most application classes do not need a finalizer. A finalizer is mainly relevant when a type directly owns unmanaged resources and follows the full dispose pattern. SafeHandle is generally preferred for wrapping native handles.

Code Example

public class NativeResourceHolder
{
    ~NativeResourceHolder()
    {
        // Finalizer: cleanup fallback for unmanaged resource.
    }
}