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 garbage collector executes finalization, not necessarily when the program exits.
- Internally, a destructor is translated by the compiler into an override of the Finalize() method.
How to use Destructor
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: The destructor is not guaranteed to run immediately when the method ends. It is executed only when the garbage collector finalizes the object.
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.