I’m reading about destructors in C# but I’m having trouble finding a decent use-case for it.
Could someone provide an example of usage with an explanation?
Much, much appreciated.
Update
The code sample in the book implements both a Desctuctor and a Dispose() method, see this code snippet from the book.
class MyClass
{
bool disposed = false; // Disposal status
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposed == false)
{
if (disposing == true)
{
// Dispose the managed resources. Factored Dispose
}
// Dispose the unmanaged resources.
}
disposed = true;
}
}
Marko
Finalizers are very rarely needed now. They used to be required when you had direct access to native resources – but now you should usually be using
SafeHandleinstead.Joe Duffy has an excellent post about this which goes into rather more details than I would be able to write myself – so go read it 🙂
A quick note on terminology: the ECMA version of the C# spec refers to them as finalizers; the Microsoft version of the spec has always referred to them as destructors and continues to do so.