Sunday, June 9, 2013

Finalize in C#

The Finalize block in C# .Net is used to clear un-managed resources before an object is destroyed. Classes / Objects which use un-managed resources should implement the Finalize method and clear all the un-managed resources they use in the Finalize block.

Unlike the Dispose() method, Finalize does not have an explicit Finalize() method in C#, instead the destructor of the class acts as the Finalize() block for the class.

The following example shows on how to declare the Destructor/Finalize block for a class.
public class Employee
{
          public void Employee()
          {
          }
          // Variables and Methods
          ~Employee()
          {
                   //Write Finalize code here to release un-managed resources.
          }
}

Both the Dispose and Finalize methods are used to clear un-managed resources, but unlike the Dispose() methods, Finalize does not have a specific method definition, in C# the destructor of the class acts as the Finalize block.

The Garbage collector keeps track of objects which implement the Finalize method, by using a Finalization queue. Before destroying an object the runtime checks if the object implements the finalize method, if so it makes a call to the objects Finalize method before actually destroying the object from memory, this gives the developers a final chance to clear un-managed resources before destroying the object.


If an object implements IDisposable, and implements the Dispose() method then there is no need to implement Finalize(), since all the all the un-managed code will be released in the dispose method. In this case the Dispose method will call GC.SuppressFinalize this will indicate the Garbage collector not to add the object to the finalize queue, and hence the Finalize will not be called for that object.

Search Flipkart Products:
Flipkart.com

No comments: