What Are Destructors?


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:
  1. class Test {  
  2.     ~Test() {  
  3.         System.Diagnostics.Trace.WriteLine("Test's Destructor is called...");  
  4.     }  
  5. }  

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:
  1. public class TestDemo {  
  2.     public TestDemo() {  
  3.             Console.WriteLine("Constructor Called...");  
  4.         }  
  6.         ~TestDemo() {  
  7.             Console.WriteLine("Destructor Called...");  
  8.         }  
  9. }  
  11. public class Demo {  
  12.     public static void Main(string[] args) {  
  13.         TestDemo objTestDemo = new TestDemo();  
  14.     }  
  15. }  
Constructor Called...
Destructor Called... 


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.