Destructors cannot be defined in structs. They are only used with classes.
A class can only have one destructor.
Destructors cannot be inherited or overloaded.
Destructors cannot be called. They are invoked automatically.
A destructor does not take modifiers or have parameters.
For example, the following is a declaration of a destructor for the class Car:
class Car
{
~Car() // destructor
{
// cleanup statements...
}
}
The destructor implicitly calls Finalize on the base class of the object. Therefore, the previous destructor code is implicitly translated to the following code:
protected override void Finalize()
{
try
{
// Cleanup statements...
}
finally
{
base.Finalize();
}
}
This means that the Finalize method is called recursively for all instances in the inheritance chain, from the most-derived to the least-derived.
Note: |
|---|
Empty destructors should not be used. When a class contains a destructor, an entry is created in the
Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance.
|
The programmer has no control over when the destructor is called because this is determined by the garbage collector. The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor (if any) and reclaims the memory used to store the object. Destructors are also called when the program exits.
It is possible to force garbage collection by calling Collect, but most of the time, this should be avoided because it may create performance issues.