Members of a Class in C#

 

As we know that a class is a collection of members. There are various kinds of members a class can have. 

The main members of Class are Fields(or variables), Methods, Constructors, Destructors, Properties, Indexers, Events, Delegates and Enumerations. 

Here we discuss about Destructors mainly. 

Destructor: Destructor is also a special method i.e., available to a class which gets called when the object of the class is destroyed. That means Destructor is opposite to a constructor. Both Constructor and Destructor methods will have the same name of class. But to discriminate between Constructor and Destructor we use tilt(~) operator before the Destructor method as shown below. 

class Employee 

{ 

        public Employee() 

         

            //this is Constructor 

        }

        ~Employee() 

         

            //this is Destructor 

        } 

} 

A destructor method cannot have any modifiers as well as parameters also. 

Destructors are basically required to perform the de-allocation of the memory. But in Managed languages like Java and C#, destructors are not necessary for de-allocation because Garbage collector will take care of them. In Managed applications if your code is completely managed, you will never need a destructor in the program where as if the code is unmanaged or we are using any unmanaged resources like files, databases....etc under the program garbage collector will not take care of those resources, memory management. So in such situations we need destructors to perform the operations like closing the file, close database connection..etc.