Unlock the Power of C# Destructors
The Role of Destructors
A destructor is a special method that’s called when an object’s scope ends. Its purpose is to release any resources held by the object, ensuring that memory is freed up for other uses. In C#, a destructor has the same name as the class and starts with a tilde (~).
A Closer Look at Destructor Syntax
public class Person
{
public Person()
{
Console.WriteLine("Constructor called");
}
~Person()
{
Console.WriteLine("Destructor called");
}
}
In this example, when we create an object of the Person
class, the constructor is called. Once the object is no longer needed, the destructor is called implicitly, releasing any resources held by the object.
More Examples and Scenarios
public class Test
{
public Test()
{
Console.WriteLine("Test constructor called");
}
~Test()
{
Console.WriteLine("Test destructor called");
}
}
Here, we create an object of the Test
class, and the constructor is called. When the object’s scope ends, the destructor is called, releasing any resources held by the object.
Key Features of Destructors
- Single Destructor per Class: You can only have one destructor in a class.
- No Access Modifiers or Parameters: A destructor cannot have access modifiers, parameters, or return types.
- Implicit Calling: A destructor is called implicitly by the Garbage collector of the.NET Framework.
- No Overloading or Inheritance: We cannot overload or inherit destructors.
- Structs Excluded: We cannot define destructors in structs.
By understanding how to properly use destructors in C#, you can write more efficient and effective code, ensuring that resources are released when no longer needed.