C# Destructor with Examples

  Keywords : c# destructor example, destructor in c# and its use, c# destructor dispose, c# destructor call example, c# destructor class, c# destructor access modifier

Here we will learn what is destructor in c# and how to use c# destructor to clear or destruct the instances of classes with examples.

C# Destructor

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 tilde (~) operator
  • The destructor in c# won’t accept any parameters and access modifiers.
  • The destructor will invoke automatically, whenever an instance of class is no longer needed.
  • The destructor automatically invoked by garbage collector whenever the class objects that are no longer needed in application.

C# Destructor Syntax

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

 

  class User

    {

        // Destructor

        ~User()

        {

            // your code

        }

    }

If you observe above syntax, we created a destructor with same class name using tilde (~) operator. Here we need to remember that destructor name must always same as class name in c# programming language.

C# Destructor Example

Following is the example of using destructor in c# programming language to destruct the unused objects of 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 class

            User user = new User();

        }

    }

}

If you observe above example, we created a class with default constructor and destructor. Here we created an instance of class “User” in Details() method and whenever the Details function execution is done, then the garbage collector (GC) automatically will invoke a destructor in User class to clear the object of class.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Destructor Example Result

 

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