Finalizers
The garbage collector provides the automatic disposal of managed resources. However, there are cases when you have to work with unmanaged resources such as raw file handles, windows, or other operating system resources retrieved with Platform Invocation Services (P/Invoke) calls, as well as COM object references in some advanced scenarios. These resources need to be explicitly released before the object is destroyed by the garbage collector; otherwise, resource leaks occur.
Every object has a special method called the finalizer. The System.Object
class has a virtual and protected member called Finalize()
, with an empty implementation. This is shown in the following code:
class Object { Â Â Â Â protected virtual void Finalize() {} }
Although this is a virtual method, you cannot actually override it directly. Instead, the C# language offers a syntax identical to the one for destructors in C++ to create a finalizer and override the System.Object
method...