.NET Finalizers

.NET Finalizers

Karol Rossa
2 min readJan 10, 2022

--

Last time we talked about Garbage Collection, it handles memory manipulation for managed code. Unfortunately, you need to release yourself unmanaged resources. Today we will discuss the first option, which is class finalizer. In a future article, I will cover how to use IDisposable.

Implementation

The Object class has an empty implementation for the Finalize method. In your types, you can’t directly override Finalize because it will yield an error.

From the description, we can see that we have to implement a destructor (finalizer) instead.

Finalizer implicitly calls Finalize on the base type. Your implementation will be translated to the following code:

Because Finalize is implicitly calling the base type Finalize, it ensures that all destructors from your class hierarchy will be executed.

In this example, the finalizer will first call Bar’s destructor, then Foo’s.
Bar’s destructor
Foo’s destructor

Remarks

We have just covered how to implement a finalizer. Now let us talk about a couple of essential things.

  • Finalizers cannot be defined in structs. They are only used with classes.
  • A class can only have one finalizer.
  • Finalizers cannot be inherited or overloaded.
  • Finalizers cannot be called. They are invoked automatically.
  • A finalizer does not take modifiers or have parameters.

It would be best to implement a finalizer only to release unmanaged resources explicitly. If you specify a destructor, only then Garbage Collector will add an instance to the finalization queue. Each item will negatively affect performance.

Destructor is called only once per instance. In some cases, you can suppress it by calling GC.SuppressFinalize. You will mostly use it in Dispose method. .NET 5 (including Core) and later versions don’t call finalizers as part of an application termination. You can’t solely depend on the finalizer to do clean up. It would help if you also used IDisposable. Which we will cover in the following article :)

--

--