In C#, destructors are special methods that are called when an object’s lifetime in memory ends and it needs to be removed from the cache. When an object is destroyed, the resources it allocated in memory are freed up and made available for other objects.
In C#, destructors are defined with the class name and have the following syntax:
~ClassName()
{
// Actions to be performed when the object is destroyed
}
Destructors are defined after the class constructor and are a special type of class method. A class can contain multiple destructors, but only the first destructor is executed.
Destructors can be used to perform special actions that need to be done before an object is removed. For example, if a file or database connection is opened, it should be closed when the object is destroyed. A destructor can be used for this purpose.
The following example demonstrates the use of a destructor in a class:
using System;
class ExampleClass
{
private int value;
public ExampleClass(int incomingValue)
{
value = incomingValue;
Console.WriteLine("Constructor method entered.");
}
~ExampleClass()
{
Console.WriteLine("Destructor executed.");
}
}
class Program
{
static void Main(string[] args)
{
ExampleClass obj = new ExampleClass(10);
Console.WriteLine("Object created.");
}
}
The above code example includes a class constructor and destructor. After creating an object with the class constructor, the program prints "Object created" to the screen. Later, when the object is destroyed at the end of the program, the destructor runs and prints "Destructor executed" to the screen.
Destructors are called by the garbage collector and manage the lifecycle of objects. Therefore, programmers often use the IDisposable interface instead of destructors to manage memory. The IDisposable interface is a more effective way to manage the lifespan of objects.
Comments
Leave a Comment