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?
UPDATE: This question was the subject of my blog in May of 2015. Thanks for the great question! See the blog for a long list of falsehoods that people commonly believe about finalization.
Almost never.
Typically one only creates a destructor when your class is holding on to some expensive unmanaged resource that must be cleaned up when the object goes away. It is better to use the disposable pattern to ensure that the resource is cleaned up. A destructor is then essentially an assurance that if the consumer of your object forgets to dispose it, the resource still gets cleaned up eventually. (Maybe.)
If you make a destructor be extremely careful and understand how the garbage collector works. Destructors are really weird:
Almost nothing that is normally true is true in a destructor. Be really, really careful. Writing a correct destructor is very difficult.
When testing the part of the compiler that handles destructors. I've never needed to do so in production code. I seldom write objects that manipulate unmanaged resources.
Destructors provide an implicit way of freeing unmanaged resources encapsulated in your class, they get called when the GC gets around to it and they implicitly call the Finalize method of the base class. If you're using a lot of unmanaged resources it is better to provide an explicit way of freeing those resources via the IDisposable interface. See the C# programming guide: http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx