0
0
CsharpConceptBeginner · 3 min read

Finalizer in C#: What It Is and How It Works

A finalizer in C# is a special method that runs automatically when an object is about to be destroyed by the garbage collector. It allows you to clean up unmanaged resources like file handles or database connections before the object is removed from memory.
⚙️

How It Works

Think of a finalizer as a cleanup crew that comes in just before a building is demolished. In C#, when an object is no longer needed, the garbage collector plans to remove it from memory. Before this happens, the finalizer method (named ~ClassName()) runs to release resources that the garbage collector can't handle on its own, such as open files or network connections.

This process is automatic but not immediate. The garbage collector decides when to run, so the finalizer might run some time after the object is no longer used. Because of this uncertainty, relying on finalizers for important cleanup is not recommended; instead, use them as a safety net.

💻

Example

This example shows a class with a finalizer that prints a message when the object is being cleaned up by the garbage collector.
csharp
using System;

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

    ~ResourceHolder()
    {
        Console.WriteLine("Finalizer called: cleaning up resources.");
    }
}

class Program
{
    static void Main()
    {
        ResourceHolder holder = new ResourceHolder();
        holder = null; // Remove reference
        GC.Collect(); // Force garbage collection
        GC.WaitForPendingFinalizers(); // Wait for finalizers to run
        Console.WriteLine("End of Main.");
    }
}
Output
ResourceHolder created. Finalizer called: cleaning up resources. End of Main.
🎯

When to Use

Use a finalizer when your class holds unmanaged resources that need to be released if the user forgets to do it manually. For example, if your class opens files, network connections, or uses unmanaged memory, a finalizer can help avoid resource leaks.

However, it's better to implement the IDisposable interface and provide a Dispose method for users to clean up resources explicitly. The finalizer acts as a backup to catch missed cleanup but should not be the primary way to release resources.

Key Points

  • Finalizers run automatically before an object is destroyed by the garbage collector.
  • They are used to clean up unmanaged resources.
  • Finalizers can delay garbage collection and affect performance.
  • Implement IDisposable for explicit cleanup and use finalizers as a safety net.
  • Finalizers have the syntax ~ClassName() in C#.

Key Takeaways

A finalizer is a special method that cleans up unmanaged resources before an object is destroyed.
Finalizers run automatically but unpredictably when the garbage collector removes an object.
Use IDisposable and Dispose for explicit cleanup; finalizers are a backup safety measure.
Finalizers can impact performance and should be used carefully.
The finalizer syntax in C# is a method named with a tilde (~) followed by the class name.