top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the significance of the Finalize method in .NET?

+2 votes
307 views
What is the significance of the Finalize method in .NET?
posted Sep 15, 2015 by Sathyasree

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

In .NET the clean activity for objects i.e when they are no longer required is done by Garbage Collector. But unmanaged resources (for example: Windows API created objects, File, Database connection objects, COM objects and so on) need to be cleaned explicitly as they are outside the scope of the .NET Framework. For this type of clean up for objects, the .NET Framework provides the "Object.Finalize" method, which can be overridden and to clean up the code for unmanaged resources. This method is automatically called by Garbage collector and thus is also called destructor of the class. As soon as object is inaccessible to application the memory acquired by the unmanaged resource is to be cleaned.
Finalize method doesn't clean the memory immediately and thus is bit expensive to use. When application runs, all object which has finalized implemented are added to Garbage collector separate queue/array i.e Garbage collector knows which object has Finalize implemented. Garbage Collector call finalize method for the objects when objects are ready to claim memory and thus removes them from the collection. Memory that is used by unmanaged resource is cleaned up when finalize method is called. Memory used by managed resource still in heap as inaccessible reference. That memory release, whenever Garbage Collector run next time. Therefore Garbage collector will not clear entire memory associated with object in fist attempt due to finalize method associated with them. So, there are two rounds for clean up when finalize is used.
Finalize and Dispose method should be used together to implement Finalize method. For Finalize, the class has declaration of destructor and this destructor after compilation becomes Finalize method.
To implement Dispose method and finalize method(destructor) for custom class, IDisposable interface is to be implemented. IDisposable interface expose Dispose method where code to release unmanaged resource will be written. The destructor(finalize) in class in turn calls Dispose method.

public class MyClass: IDisposable
{
public MyClass() //Construcotr
{
//Initialization:
}
~MyClass() //Destrucor also called Finalize
{
this.Dispose();
}
public void Dispose()
{
//write code to release unmanaged resource.
}
}
answer May 24, 2016 by Manikandan J
...