Saturday, 15 November 2025

C# Destructors

C# Destructors Explained

What is a Destructor?

A destructor is a special method in C# used to clean up resources when an object is no longer needed or is about to be destroyed. Destructors are automatically called by the garbage collector.

Key Points About Destructors

  • Called automatically before an object is destroyed.
  • Cannot take parameters.
  • Does not return any value.
  • Named with a tilde (~) before the class name.
  • Used to release resources like memory, files, or database connections.

Syntax Example

using System;

class Car
{
    public string Model;

    // Constructor
    public Car(string model)
    {
        Model = model;
        Console.WriteLine($"{Model} object created.");
    }

    // Destructor
    ~Car()
    {
        Console.WriteLine($"{Model} object destroyed.");
    }
}

class Program
{
    static void Main()
    {
        Car myCar = new Car("BMW");
        Car anotherCar = new Car("Audi");

        Console.WriteLine("End of Main method.");
    }
}

    

Possible Output

BMW object created.
Audi object created.
End of Main method.
BMW object destroyed.
Audi object destroyed.
    

Constructor vs Destructor

Feature Constructor Destructor
Purpose Initialize object Clean up before object is destroyed
Parameters Can have parameters Cannot have parameters
Return Type None None
Call Automatically when object is created Automatically when object is destroyed (GC)
Naming Same as class ~ClassName

No comments:

Post a Comment