Finalize Method in C#

Kailash Chandra Behera | Sunday, August 07, 2016

Introduction

This article describes about Finalize Method and demonstrates how to use Finalize method in C# programming.

Getting Started

Finalize method is used to perform cleanup operations on unmanaged resources that are no longer used (For example, Windows API created objects, File, Database connection objects, COM objects, etc) and held by the current object before the object is destroyed. This method is internally called by Garbage Collector whenever the object goes out of scope, hence the object will not free immidately.

This method makes Grabage Collector visit twice, hence it effects performance of your programm. So it is recommended that not to use Finalize method until it is extremely necessary. Whenever you use Finalize method also implement IDisposable.Dispose with GC.SuppressFinalize.

This method is protected and therefore is accessible only through this class or through a derived class. In inheritance, the chain Finalize method is called from the most-derived to the least-derived means the topmost base class Finalizes get called at last.

Finalize method is impementing by destructor of class. When destructor is declared in class, the destructor of class implicitly calls Finalize of base class of the object.

 class Student  
 {  
   ~Student() // destructor  
   {  
     // cleanup statements...  
   }  
 }  

Summary

In this article we have discussed about Finalize method and how to use Finalize method, Hope this article may helpful to you.

Thanks