For example:
public class Person
{
public Person()
{
}
~Person()
{
}
}
When should I manually create a destructor? When have you needed to create a destructor?
For example:
public class Person
{
public Person()
{
}
~Person()
{
}
}
When should I manually create a destructor? When have you needed to create a destructor?
The C# language calls these "destructors", but most people call them "finalizers" since that is their .NET name and it reduces confusion with C++ destructors (which are quite different).
How to Implement IDisposable and Finalizers: 3 Easy Rules
It's called a destructor/finalizer, and is usually created when implementing the Disposed pattern.
It's a fallback solution when the user of your class forgets to call Dispose, to make sure that (eventually) your resources gets released, but you do not have any guarantee as to when the destructor is called.
In this Stack Overflow question, the accepted answer correctly shows how to implement the dispose pattern. This is only needed if your class contain any unhandeled resources that the garbage collector does not manage to clean up itself.
A good practice is to not implement a finalizer without also giving the user of the class the possibility to manually Disposing the object to free the resources right away.
You don't need one unless your class maintains unmanaged resources like Windows file handles.
It's called a "finalizer", and you should usually only create one for a class whose state (i.e.: fields) include unmanaged resources (i.e.: pointers to handles retrieved via p/invoke calls). However, in .NET 2.0 and later, there's actually a better way to deal with clean-up of unmanaged resources: SafeHandle. Given this, you should pretty much never need to write a finalizer again.
When you have unmanaged resources and you need to make sure they will be cleaned up when your object goes away. Good example would be COM objects or File Handlers.
I have used a destructor (for debug purposes only) to see if an object was being purged from memory in the scope of a WPF application. I was unsure if garbage collection was truly purging the object from memory, and this was a good way to verify.