C Sharp Destructor

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# Destructor

A destructor works opposite to constructor, It destructs the objects of classes. It can be defined only once in a class. Like constructors, it is invoked automatically.

Note: C# destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.

C# Constructor and Destructor Example

Let's see an example of constructor and destructor in C# which is called automatically.

  1. using System;  
  2.    public class Employee  
  3.     {  
  4.         public Employee()  
  5.         {  
  6.             Console.WriteLine("Constructor Invoked");  
  7.         }  
  8.         ~Employee()  
  9.         {  
  10.             Console.WriteLine("Destructor Invoked");  
  11.         }  
  12.     }  
  13.    class TestEmployee{  
  14.        public static void Main(string[] args)  
  15.         {  
  16.             Employee e1 = new Employee();  
  17.             Employee e2 = new Employee();  
  18.         }


Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked

Note: Destructor can't be public. We can't apply any modifier on destructors.