Introduction
C# is a garbage collector, meaning that the framework will free an object that you no longer need to use. There may be times where you need to do some manual cleanup. A destructor is a method that's called once an object is disposed of, and can be used to clean up resources used by the object.
- Destructors cannot be defined in structs. They are only used with classes.
- A class can only have one destructor.
- Destructors cannot be inherited or overloaded.
- Destructors cannot be called. They are invoked automatically.
- A destructor does not take any parameters or have modifiers.
- We can define a destructor using the Tilde symbol(~).
We can declare a destructor in a class by using the below syntax:
- class Test {
- ~Test() {
- System.Diagnostics.Trace.WriteLine("Test's Destructor is called...");
- }
- }
Difference between Constructor and Destructor
- A Constructor is a special method that is called automatically each time when an object is created.
- Destructors cannot be called. They are invoked automatically.
- The method with the same name as the class name can be called a constructor.
- A destructor is just the opposite of a constructor. since it gets invoked when the object goes out of scope.
- Like a Constructor, we have same name as the class name with a Destructor as well. We mention this same name with the Tilde symbol(~)
- Constructors can accept parameters in method while passing.
- The destructor does not have any modifiers or have parameters.
- We can overload constructors.
- We cannot overload a Destructor nor inherit it.
Below is an example of a Constructor and Destructor:
- public class TestDemo {
- public TestDemo() {
- Console.WriteLine("Constructor Called...");
- }
-
- ~TestDemo() {
- Console.WriteLine("Destructor Called...");
- }
- }
-
- public class Demo {
- public static void Main(string[] args) {
- TestDemo objTestDemo = new TestDemo();
- }
- }
Output
Constructor Called...
Destructor Called...
Conclusion
Here we understand the definition of Destructor as well as the difference between a Constructor and Destructor. I hope this will clear your doubts about destructors. If you have any queries, you can comment and I will answer as soon as possible.