C# Destructor with Examples

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.

 

  • In c#, destructors can be used only in classes, and a class can contain only one destructor.
  • The destructor in class can be represented by using the tilde (~) operator
  • The destructor in c# won’t accept any parameters and access modifiers.
  • The destructor will invoke automatically whenever an instance of a class is no longer needed.
  • The garbage collector automatically invokes the destructor whenever the class objects are no longer needed in the application.

C# Destructor Syntax

Following is the syntax of defining a destructor in the c# programming language.

 

class User
{
   // Destructor
   ~User()
   {
     // your code
   }
}

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.

C# Destructor Example

Following is the example of using a destructor in c# programming language to destruct the unused objects of a class.

 

using System;

namespace Tutlane
{
    class User
    {
       public User()
       {
           Console.WriteLine("An Instance of class created");
       }
       // Destructor
       ~User()
       {
          Console.WriteLine("An Instance of class destroyed");
       }
    }
    class Program
    {
       static void Main(string[] args)
       {
          Details();
          GC.Collect();
          Console.ReadLine();
       }
       public static void Details()
       {
          // Created instance of the class
          User user = new User();
       }
    }
}

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.

 

C# Destructor Example Result

 

This is how we can use a destructor in c# programming language to clear or destruct unused objects based on our requirements.