Steps to Override Finalize in C#

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


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 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.


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

  1. public class MyClass  
  2. {  
  3.    protected override void Finalize()  
  4.    {  
  5.       // Do unmanaged resource clean up here  
  6.    }  
  7. }  

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

Ohh, the code above does not build. Let's look at the 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.

  1. public class MyClass  
  2. {  
  3.    ~MyClass()  
  4.    {  
  5.       // Do unmanaged resource clean up here  
  7.       Console.WriteLine("In destructor");  
  8.    }  
  9. }  

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

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

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 Idisposable interface. Using it a user can dispose of an object whenever required. But one thing to keep in mind is that dispose will only do its job when developers specifically call the dispose method and if they missed 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