In the destructor, we need to write code to release unmanaged resources (file handles, network connections, low-level database connections, and so on).
Read more:
write code to properly release unmanaged resources in the destructor and in the interface IDisposable in the C# ...
Note 1! The class destructor has no return type.
Note 2! The name of the destructor is always the same as the name of the class.
Example
C#
class Car
{
// destructor
~Car()
{
// cleanup
// ...
}
}
1)
Garbage collector finds which objects are not needed.
2) The garbage collector will call the destructor.
3) The garbage collector will delete the object from memory.
In reality in item 2)
The garbage collector will not call the destructor. The garbage collector will call the
Finalize.
Method
Finalize causes a destructor.
Just like that:
C#
protected override void Finalize()
{
try
{
// destructor call
}
finally
{
base.Finalize();
}
}
The call to the destructor is determined by the garbage collector.
The garbage collector checks for objects that are no longer used by the application.
If the garbage collector believes that an object needs to be destroyed, it calls a destructor (if any) and releases the memory used to store that object. Destructors are also invoked when the program exits.
It is possible to force garbage collection by calling the Collect, but in most cases this should be avoided because it can lead to performance issues.