Finalizer in C#: What It Is and How It Works
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
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."); } }
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
IDisposablefor explicit cleanup and use finalizers as a safety net. - Finalizers have the syntax
~ClassName()in C#.