In C# what is the difference between a destructor and a Finalize method in a class?

Jeff Leonard picture Jeff Leonard · Jul 3, 2009 · Viewed 66.8k times · Source

What is the difference, if there is one, between a destructor and a Finalize method in a class?

I recently discovered that Visual Studio 2008 considers a destructor synonymous with a Finalize method, meaning that Visual Studio won't let you simultaneously define both methods in a class.

For example, the following code fragment:

class TestFinalize
{
    ~TestFinalize()
    {
        Finalize();
    }

    public bool Finalize()
    {
        return true;
    }
}

Gives the following error on the call to Finalize in the destructor:

The call is ambiguous between the following methods or properties: 'TestFinalize.~TestFinalize()' and 'TestFinalize.Finalize()'

And if the call to Finalize is commented out, it gives the following error:

Type 'ManagementConcepts.Service.TestFinalize' already defines a member called 'Finalize' with the same parameter types

Answer

Kenzi picture Kenzi · Nov 28, 2011

Wikipedia has some good discussion on the difference between a finalizer and a destructor in the finalizer article.

C# really doesn't have a "true" destructor. The syntax resembles a C++ destructor, but it really is a finalizer. You wrote it correctly in the first part of your example:

~ClassName() { }

The above is syntactic sugar for a Finalize function. It ensures that the finalizers in the base are guaranteed to run, but is otherwise identical to overriding the Finalize function. This means that when you write the destructor syntax, you're really writing the finalizer.

According to Microsoft, the finalizer refers to the function that the garbage collector calls when it collects (Finalize), while the destructor is your bit of code that executes as a result (the syntactic sugar that becomes Finalize). They are so close to being the same thing that Microsoft should have never made the distinction.

Microsoft's use of the C++'s "destructor" term is misleading, because in C++ it is executed on the same thread as soon as the object is deleted or popped off the stack, while in C# it is executed on a separate thread at another time.