Destructor


In this article we are going to discuss about destructor with examples in C#.

Destructor

A destructor in C# is a special method inside the class used to destroy instances of that class when they are no longer needed. Destructors are particularly useful for releasing unmanaged resources like file handles, database connections, or unmanaged memory that the .NET garbage collector does not handle automatically.

The Destructor is called implicitly by the .NET Framework’s Garbage collector.

Features of Destructors

  1. No Parameters - Destructors cannot have parameters.
  2. No Access Modifiers - They cannot have access modifiers (e.g., public, private, etc.). They are always implicitly private.
  3. Automatic Invocation - Destructors are called automatically by the garbage collector, so you do not invoke them explicitly.
  4. Only One Destructor - A class can have only one destructor.

Syntax

The syntax for defining a destructor is similar to that of a constructor but with a tilde (~) before the class name.

class MyClass
{
    // Destructor
    ~MyClass()
    {
        // Cleanup code
    }
}

When to Use Destructors

  1. Unmanaged Resources - When dealing with unmanaged resources that the garbage collector cannot clean up.
  2. Final Safety Net - As a backup to the Dispose method to ensure resources are released if Dispose is not called.

Prev Next