A destructor is the opposite of a constructor. A destructor destroys the object of a class as soon as the scope of an object ends. It is also invoked automatically just like a constructor.
The destructor cannot have parameters nor modifiers.
Syntax of destructor in C#
The destructor has the exact same name as the class, the difference is, it is prefixed with a tilde sign (~).
//Syntax
~ClassName()
//Example
using System;
namespace program
{
class Square
{
~Square() // destructor
{
// statement
}
}
}
let us see an example of a destructor in C#.
Example of constructor and destructor in C#
using System;
namespace program
{
public class Student
{
public int roll;
public String name;
public float score;
//constructor
public Student(int r, String n, float s)
{
roll = r;
name = n;
score = s;
}
public void display()
{
Console.WriteLine(roll + " " + name + " " + score);
}
//Destructor
~Student()
{
Console.WriteLine("Destructor invoked");
}
}
class StudenInfo
{
public static void Main(string[] args)
{
Student std1 = new Student(1101, "Shaun", 80.5 f);
Student std2 = new Student(1102, "Garen", 90 f);
std1.display();
std2.display();
}
}
}
Output:
1101 Shaun 80.5
1102 Garen 90
Destructor invoked
Destructor invoked