Wednesday, 20 July 2011

Difference between Destructor and Finalize() method in C#

Finalize() Method of Object class
Each class in C# is automatically (implicitly) inherited from the Object class which contains a method Finalize(). This method is guaranteed to be called when your object is garbage collected (removed from memory). You can override this method and put here code for freeing resources that you reserved when using the object.

Example of Finalize Method
Protected override void Finalize()
                   Console.WriteLine(“Destructing Object….”);//put some code here.

1) A destructor is just opposite to constructor.
2) It has same as the class name, but with prefix ~ (tilde).
3) They do not have return types, not even void and therefore they cannot return values.
4) Destructor is invoked whenever an object is about to be garbage collected.

Example of Destructor in .Net
class person

                   //put resource freeing code here.

Difference between the destructor and the Finalize() method
Finalize() corresponds to the .Net Framework and is part of the System.Object class. Destructors are C#'s implementation of the Finalize() method.
The functionality of both Finalize() and the destructor is the same, i.e., they contain code for freeing the resources when the object is about to be garbage collected.
In C#, destructors are converted to the Finalize() method when the program is compiled.
The Finalize() method is called by the .Net Runtime and we cannot predict when it will be called. It is guaranteed to be called when there is no reference pointing to the object and the object is about to be garbage collected.

1 comment: