04 Feb C# Destructors
A Destructor destructs an object. It has the same name as the class name and gets automatically called when an object gets created like Constructors.
Syntax – Destructors
Let us see the syntax of Destructors with our class name Studyopedia. It is prefixed by a tilde sign as shown below:
1 2 3 4 5 6 7 8 |
Studyopedia() { // Constructor // Code comes here } ~Studyopedia() { // Destructor // Code comes here } |
As shown above, the Destructor syntax is like the Constructor, except for the prefixed tilde sign. Remember, the following points about Destructors:
- Define Destructor only once in a class
- Destructors cannot return a value
- Destructors cannot have parameters like Constructors.
- The Destructors cannot be overloaded.
- The Destructors cannot be inherited.
Example – Destructors
Let us now see an example of Destructors 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 |
using System; namespace Demo { class Rectangle { // Constructor name is the same as the class name Rectangle() { Console.WriteLine("The Constructor!!"); Console.WriteLine("A rectangle has 4 sides, 4 corners, and 4 right angles"); } // Destructor name is the same as the class name with a prefixed tilde sign ~Rectangle() { Console.WriteLine("\Destructor gets invoked automatically!!"); } static void Main(string[] args) { /* Constructor and Destructor gets called automatically when we create an object of a class */ Rectangle rct = new Rectangle(); } } } |
Output
1 2 3 4 5 6 |
The Constructor!! A rectangle has 4 sides, 4 corners, and 4 right angles Destructor gets invoked automatically!! |
No Comments