Article

Destructor


Destructor

Destructor is opposite of constructor.It is used to destructs automatically the instance of the constructor class.it is defined one time in the class. It is defined by the tilde(~) operator with no parameters and access modifier. In another form it is just like garbage collector that is used to destructs the objects of constructor class automatically after execution of the code. it's name is same as class name with tilde(~)operator.


using System;

namespace MyCode
{

class MyClass
    {
        
        public MyClass()
        {
            Console.WriteLine("This is Constructor of MyClass");
        }

       
        ~MyClass()
        {
            Console.WriteLine("This is Destructor of MyClass");
        }
    }
  class Program
  {
    static void Main(string[] args)
        {
            
            MyClass obj = new MyClass(); //object of MyClass Constructor Created.

            Console.Read(); 
            
            //object of constructor class destroy automatically.
        }
    
    }
  }
  
 
OUTPUT 

This is Constructor of MyClass
This is Destructor of MyClass