C# Destructor

Learn what destructors are in C#, how they work, and when the .NET runtime calls them to clean up unmanaged resources.

What is a Destructor?

A destructor in C# is a special method used to perform cleanup operations before an object is removed from memory by the garbage collector. It is defined using a tilde (~) followed by the class name.

How Destructors Work

Unlike constructors, destructors are called automatically by the garbage collector and cannot be called explicitly, nor can they accept parameters or access modifiers, and a class can only have one destructor.

Destructors vs Dispose Pattern

Because the timing of garbage collection is non-deterministic, destructors are not ideal for releasing critical unmanaged resources promptly. The recommended approach is implementing IDisposable alongside a destructor as a safety net.

When to Use Destructors

Destructors are best reserved for classes that directly hold unmanaged resources, such as file handles or database connections, as a fallback cleanup mechanism rather than the primary resource management strategy.

Conclusion: While destructors are rarely needed in everyday C# programming thanks to automatic garbage collection, understanding how they work is important when dealing with unmanaged resources and building robust, leak-free applications.

Writing a Destructor: Syntax and a First Example

A destructor (also called a finalizer) is declared with a tilde and the class name. It has no return type, no parameters and no access modifier.

class LogWriter
{
    public LogWriter()
    {
        Console.WriteLine("LogWriter created");
    }

    ~LogWriter()
    {
        Console.WriteLine("Finalizer running");
    }
}

Behind the scenes, the compiler turns this into an override of Object.Finalize() and wraps your code so the base class finalizer is also called. You never call it yourself; the runtime decides when.

What Happens During Finalization

  1. When an object with a finalizer is created, the runtime notes that it must be finalized later.
  2. When the garbage collector finds the object is no longer reachable, it does not free the memory straight away. It puts the object in a finalization queue.
  3. A dedicated finalizer thread runs the destructor code.
  4. Only in a later collection is the memory actually reclaimed.

This means objects with finalizers live longer and cost more to collect. That is the main reason you should not add a destructor to a class "just in case".

You can watch this happen in a small console app: create objects in a loop, drop the references, then call GC.Collect() followed by GC.WaitForPendingFinalizers(). The finalizer messages appear only after those calls. Forcing a collection is fine for experiments, but production code should almost never do it.

The Dispose Pattern in Practice

The safer approach is to clean up deterministically with IDisposable and keep the finalizer only as a backup. Here is the standard shape:

class NativeBuffer : IDisposable
{
    private IntPtr handle;
    private bool disposed;

    public NativeBuffer(int size)
    {
        handle = Marshal.AllocHGlobal(size);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);   // finalizer no longer needed
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposed) return;
        if (disposing)
        {
            // release other managed IDisposable objects here
        }
        Marshal.FreeHGlobal(handle);   // unmanaged cleanup
        disposed = true;
    }

    ~NativeBuffer()
    {
        Dispose(false);
    }
}

Callers then use a using statement, which calls Dispose() automatically even if an exception is thrown:

using (var buffer = new NativeBuffer(1024))
{
    // work with buffer
}   // Dispose() runs here

In modern .NET, wrapping raw handles in a SafeHandle subclass is often better still, because the framework then handles the finalization logic for you.

Common Mistakes with Destructors

  • Touching other managed objects inside the finalizer. They may already have been finalized. Only release unmanaged resources there.
  • Expecting it to run at a specific moment. It may run much later, and there is no guarantee it runs at all when a process is shutting down.
  • Throwing exceptions from it. An unhandled exception on the finalizer thread can terminate the process.
  • Adding an empty destructor. It still puts every instance on the finalization queue and slows collection down.
  • Forgetting GC.SuppressFinalize after a successful Dispose(), which wastes work.

Rule of thumb: if your class holds only managed objects, implement IDisposable without a destructor. Add a destructor only when the class directly owns an unmanaged resource.

Ready to Master C# Programming Course?

Join Uncodemy's hands-on training program with expert mentors and real-world projects.