C# - Destructors
A destructor is a special method of a class which destructs or deletes an object and automatically executed when the object goes out of scope. An object goes out of scope when:
- the method containing object ends.
- the program ends.
- a block containing local object variable ends.
- a delete operator is called for an object.
Create Destructor
To create a destructor in C#, there are certain rules which need to be followed:
- Destructor should begin with tilde sign(~) followed by class name.
- A class can have only one destructor.
- Unlike constructors that can have parameters, destructors do not allow any parameter.
- Destructor do not have any return type, just like constructors.
- When a destructor is not specified in a class, compiler generates a default destructor and inserts it into the code.
Syntax
//Creating class destructor ~className() { statements; }
Example:
In the example below, a class called Circle is created. A constructor and destructor are also created. The destructor prints a message before deleting the object and called automatically when a object goes out of scope (program ends in this example).
using System; class Circle { //class member field int radius; //class constructor public Circle(int x) { radius = x; } //class destructor ~Circle() { Console.WriteLine("Destructor invoked."); } //class method public double area() { return 22/7.0*radius*radius; } static void Main(string[] args) { Circle Cir1 = new Circle(5); Circle Cir2 = new Circle(10); Console.WriteLine(Cir1.area()); Console.WriteLine(Cir2.area()); } }
The output of the above code will be:
78.5714285714286 314.285714285714 Destructor invoked. Destructor invoked.