Junior — Middle
Can you explain what a destructor is in object-oriented programming?
sobes.tech AI
Answer from AI
A destructor in object-oriented programming is a special class method that is automatically called when an object is deleted or when it goes out of scope. Its main task is to release resources that the object may have acquired during its lifetime, such as closing files, freeing memory, or network connections.
In C#, a destructor looks like a method with the class name, but with a tilde (~) before it:
class MyClass
{
~MyClass()
{
// code to clean up resources
}
}
It is important to remember that destructors in C# operate within the garbage collection mechanism and do not guarantee an immediate call, so for releasing managed resources, it is better to use the IDisposable interface and the Dispose() method.