Steps To Override Finalize In C#

Introduction

In this article, we will learn the importance of the Finalize method and the issues when overriding it in C#. And finally, how to remedy the problem.

Background

Being a .NET Developer, you must have basic information about the Garbage Collector. The Garbage Collector is a boon for .Net developers that takes care of memory management for .NET programs in the background. But as we know, there are some limitations as well. The Garbage Collector can collect only managed objects. So what about unmanaged objects?

The Garbage Collector cannot clean up unmanaged objects properly because these objects do not exist within the .NET Framework, and the CLR does not have control of them. So it is the developer's responsibility to clean up unmanaged resources. It is advised to override the Finalize method (that is, a virtual method in the Object class) to clean up the unmanaged resources. The Garbage Collector calls the finalize method of each object (that has overridden the Finalize method) during the collection process. So let's see how to do that.

Example. Let's create a class and override the Finalize method as in the following.

public class MyClass
{
    protected override void Finalize()
    {
        // Do unmanaged resource cleanup here
    }
}

For simplicity, I just overrode the Finalize method. Now let's build the code.

Oh, the code above does not build. Let's look at the error.

error

So we can see that it gives an error. It is self-describing, saying to use a destructor instead of overriding the Finalize method. It shows that C# does not allow overriding the Finalize method. But Why?

So before discussing it, let's change the class definition and use a destructor (destructor in any class starts with a tilde (~)) itself.

public class MyClass
{
    ~MyClass()
    {
        // Do unmanaged resource clean up here
        Console.WriteLine("In destructor");
    }
}

So let's build it now. It successfully builds without any error.

Let's see this class under the hood via Reflector.

finalize

In the above image, we can see that the C# compiler itself converted the destructor to Finalize. So actually, it means that the destructor and Finalize are the same in C#. And C# actually does now allow overriding, whereas, for the CLR, it is the same as overriding the Finalize method.

Note. Normally, we don't override Finalize or provide a destructor but instead rely on the Disposable interface. Using it, a user can dispose of an object whenever required. But one thing to keep in mind is that disposal will only do its job when developers specifically call the disposal method, and if they miss it, then the GC won't be able to handle it. So it is better that one should have both so if in case one misses calling the dispose method, then GC handles it gracefully.


Similar Articles