The Wayback Machine - https://web.archive.org/web/20260227050644/https://www.geeksforgeeks.org/c-sharp/destructors-in-c-sharp/

Destructors in C#

Last Updated : 13 Sep, 2025

A destructor in C# is a special method that is automatically called when an object is destroyed or removed from memory. It is used to release unmanaged resources like file handles, database connections or network streams before the object is reclaimed by the garbage collector.

Syntax

class ClassName {

// Destructor

~ClassName() {

// Cleanup code

}

}

  • Declared using a tilde (~) followed by the class name.
  • Cannot have access modifiers or parameters.
  • A class can have only one destructor.
  • Cannot be called explicitly, it is invoked automatically by the garbage collector.
  • Useful for cleaning up unmanaged resources, but not necessary for managed memory.
  • It cannot be defined in Structures. It is only used with classes.
  • It cannot be overloaded or inherited.
  • It is called when the program exits.
  • Internally, the Destructor is called the Finalize method on the base class of the object.

How to use Destructor

C#
using System;

class Geeks 
{
    // Constructor
    public Geeks() 
    {
        Console.WriteLine("Object Created.");
    }

    // Destructor
    ~Geeks() 
    {
        Console.WriteLine("Object Destroyed.");
    }

    public void DisplayMessage() 
    {
        Console.WriteLine("Message Printed.");
    }

    public static void Main(string[] args)
    {
        // Create an instance of Geeks
        Geeks g = new Geeks();
      
        // Destructor will be called when g goes out of scope
        g.DisplayMessage();
    }
}

Output
Object Created.
Message Printed.
Object Destroyed.

Explanation: Constructor is called when the new object is created, after which all the operations are performed. At the end, before Main method is exited all the object elements are destroyed.

Note:

Destructor is mainly used to release resources like memory, file handles or database connections, ensuring that no resources are left hanging when an object goes out of scope.

Suggested Quiz

0 Questions

Quiz Completed Successfully

Your Score : 0/0

Accuracy : 0%

Comment
Article Tags:

Explore