Dispose and Finalize Method
Dispose and Finalize Method?
To help prevent resource leaks for unmanaged resources, the garbage collector calls a special method named Finalize on each object before it is removed from the memory. The finalize method is called by the garbage collector to perform termination housekeeoing on an object (such as releasing unmanaged resources used by the object) just before the garbage collector reclaims the object's memory. Method finalize does not take parameters and does not return a value.
finalize() method is automatically invoked by .net runtime environment to destroy objects which are out of scope. It works as a garbage collector. You donot give body to finalize() and you can not explicitly calll it. The garbage collector calls this method at some point after there are no longer any valid references to the object.
In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object. Dispose can be called even if other references to the object are alive.
Note that even when you provide explicit control by way of Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose.