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 (~).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //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#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 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