c-sharp
  1. c-sharp-destructor

C# Destructor

Syntax

~ClassName()
{
    // Code
}

Example

class Car
{
    public Car()
    {
        Console.WriteLine("Car object created");
    }

    ~Car()
    {
        Console.WriteLine("Car object destroyed");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car();
        // code
    }
}

Output

Car object created
Car object destroyed

Explanation

C# Destructor is a method that is used to free the resources that are used by an object before it is destroyed. It is called automatically when the object is no longer in use or when the Garbage Collector is disposing of the object.

The destructor looks like a method with the same name as the class and is prefixed with '~'. It does not have any parameters and is not used to return any value. It is the last method to be called before the object is destroyed, and it cannot be called explicitly.

Use the destructor to release the unmanaged resources that are associated with an object, such as file handles, database connections, and network connections.

Use

The C# Destructor is used when an object is longer in use or when the Garbage Collector is disposing of the object. It is used to free the resources that are used by an object. It can be used to release unmanaged resources, such as file handles, database connections, and network connections.

Important Points

  • The destructor looks like a method with the same name as the class but is prefixed with '~'.
  • The destructor does not have any parameters and is not used to return any value.
  • It is called when the object is no longer in use or when the Garbage Collector is disposing of the object.
  • Use the destructor to release the unmanaged resources that are associated with an object.

Summary

The C# Destructor is used to free the resources that are used by an object before it is destroyed. It is called automatically when the object is no longer in use or when the Garbage Collector is disposing of the object. Use it to release unmanaged resources, such as file handles, database connections, and network connections. As it is called automatically, you do not need to use it explicitly in your code.

Published on: