In c#, Destructor is a special method of a class, and it is used in a class to destroy the object or instances of classes. The destructor in c# will invoke automatically whenever the class instances become unreachable.
Following are the properties of destructor in c# programming language.
Following is the syntax of defining a destructor in the c# programming language.
If you observe the above syntax, we created a destructor with the same class name using the tilde (~) operator. Here, you need to remember that the destructor name must be the same as the class name in the c# programming language.
Following is the example of using destructor in c# programming language to destruct the unused objects of a class.
If you observe the above example, we created a class with a default constructor and destructor. Here we created an instance of class “User” in the Details() method, and whenever the Details function execution is done, then the garbage collector (GC) automatically will invoke a destructor in the User class to clear the object of a class.
When you execute the above c# program, you will get the result below.
This is how we can use destructor in c# programming language to clear or destruct unused objects based on our requirements.