C# Destructor
Learn what destructors are in C#, how they work, and when the .NET runtime calls them to clean up unmanaged resources.
What is a Destructor?
A destructor in C# is a special method used to perform cleanup operations before an object is removed from memory by the garbage collector. It is defined using a tilde (~) followed by the class name.
How Destructors Work
Unlike constructors, destructors are called automatically by the garbage collector and cannot be called explicitly, nor can they accept parameters or access modifiers, and a class can only have one destructor.
Destructors vs Dispose Pattern
Because the timing of garbage collection is non-deterministic, destructors are not ideal for releasing critical unmanaged resources promptly. The recommended approach is implementing IDisposable alongside a destructor as a safety net.
When to Use Destructors
Destructors are best reserved for classes that directly hold unmanaged resources, such as file handles or database connections, as a fallback cleanup mechanism rather than the primary resource management strategy.
.png)