Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
Finalize is an object method that contains the code required to free unmanaged resources and perform cleanup operations prior to garbage collection (GC).
The finalize method is used to clean up resources not managed by .NET. Although the .NET framework is designed to release managed resources by implicitly performing memory management tasks, unmanaged application resources - like file handles and database connections - must be explicitly released.
While finalize is designed to be implicitly called by GC, the dispose method may be explicitly called by user code to free resources.
Finalize is similar to traditional C++ destructors, as each is responsible for freeing object resources. C++ destructors are executed immediately when an object goes out of scope, whereas finalize is called during object cleanup at GC. In C#, finalize cannot be directly called or overridden. If a destructor is declared, it is converted to the finalize method when the program is compiled.
During finalize, memory allocation or calling virtual methods must be avoided. The scope of finalize should be protected so that it is only accessed within the same class or its derived class. Finalize should not reference any other objects. In C#, calling finalize directly on an object other than its base class is an invalid operation. Finalization code should be minimal without any calls capable of blocking the calling thread. As finalize is called by a dedicated thread, its code should not use thread local storage or any technique requiring thread affinity.
Using finalize as a fallback mechanism for releasing unmanaged memory or resources is essential, due to lack of determinism and effects on GC performance.