Tuesday, 20 September 2011

Difference between finalize , destructor

.Net managed code enjoy's benefits of CLR, which automatically checks for object scope and if it is not referenced by any object than it is removed from memory.

But you can also manually frees memory
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()
{
try
{
Console.WriteLine(“Destructing Object….”);//put some code here.
}
finally
{
base.Finalize();
}
}

Destructor
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
{
//constructor
person()
{
}
//destructor
~person()
{
//put resource freeing code here.
}
}

What is the difference between the destructor and the Finalize() method? When does the Finalize() method get called?
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 can not 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.

No comments:

Post a Comment