A destructor in C# is a special method that is automatically called when an object is destroyed or no longer needed. It is used to clean up resources, such as closing files or releasing memory, before the object is removed from memory by the garbage collector.
Destructors are similar to finalizers in C++, and they allow you to perform clean-up operations such as closing files, releasing unmanaged resources, or disconnecting from databases.
A destructor is defined using the ~ symbol followed by the class name, and it doesn’t take any parameters or return any value.
Syntax:
class ClassName
{
// Destructor
~ClassName()
{
// Code to release resources
}
}
Example:
using System;
class MyData
{
// Constructor
public MyData()
{
Console.WriteLine("MyData object created.");
}
// Destructor
~MyData()
{
// Code to release unmanaged resources or perform cleanup
Console.WriteLine("MyData object destroyed.");
}
}
class Program
{
static void Main()
{
MyData mydata = new MyData();
// Normally, destructor is called when the object is garbage collected,
// but to force the garbage collection in this example, we call GC.Collect.
// In real programs, you don't call this explicitly.
GC.Collect(); // This forces the garbage collector to run
Console.WriteLine("Main method completed.");
}
}
Output:
MyData object created.
Main method completed.
MyData object destroyed.
Main method completed.
MyData object destroyed.