Destructor in C#


In the previous tutorial, we discussed constructor in C# . In this C# tutorial, we are going to learn C# destructor. The destructor is the opposite of the constructor. If you are already leaned constructor, it will be easy for you.

The destructor is a special class function that destroys the object as soon as the scope of the object end. In C# programming, the destructor is called automatically by the compiler when the object goes out of scope. The destructors is also called automatically.

C# destructor can be defined once in a class. 

Let's understand the C# destructor through syntax. The syntax of the destructor is similar to the syntax of the constructor, the same class name is used for a name for C# destructor with a tilde ~ sign as the prefix to it.
In simple words -


C# constructor is created by the same name of the class without any special sign but if you want to create destructor, you have to use tilde ~ sign with the same class name.


C# destructor syntax -


class Hello
{
    public:
    // defining destructor for class Hello 
    ~Hello() 
    {
        // statement
    }   
};

In the above syntax, you can see the destructor is created with tilde sign. The destructor cannot have any arguments.

 

Example of C# constructor and destructor- 


In this example, we are going to create a simple class. In this C# example, we will create constructor and destructor with the same name of class. We will create an object of class and see when a constructor is called and when a destructor gets called.


using System;  
   public class Student 
    {  
           public string name; 
           public double roll_no;
        
        
        public Student()  
        {  
            Console.WriteLine("Constructor called");  
        }  
        ~Student()  
        {  
            Console.WriteLine("Destructor Called");  
        }  
      
    }  
   class TestStudent{  
       public static void Main(string[] args)  
        {  
            Student obj1 = new Student();  
            Student obj2 = new Student(); 
        
           
       
        }  
    }  

Output -

Constructor called
Constructor called
Destructor Called
Destructor Called


When an object is created the constructor and destructor of that class are called.