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 SafeHandle
instead.
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.
They're finalizers, not destructors. They're often used to clean up unmanaged resources - if you wrote your own file class, then you would need to use the finalizer to clean up the native file handle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With