I have seen the code below a lot of times in different threads and different forums. This one in particular I picked up from How does GC and IDispose work in C#?.
class MyClass : IDisposable
{
...
~MyClass()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{ /* dispose managed stuff also */ }
/* but dispose unmanaged stuff always */
}
}
My questions are:
-
Is it necessary to create an explicit destructor? The class inherits from IDisposable and during GC cleanup Dispose() will be eventually executed.
-
What is the significance of the parameter ‘disposing’ in Dispose(bool disposing)? Why is it necessary to differentiate between disposing of managed and unmanaged objects?
1: no; that is common only in classes that directly wrap an external unmanaged resource, such as windows-handles; or if it is possible that some subclass will do such. If you are only handling managed objects, adding a finalizer is actually a bad thing, in that it impacts the wat collection works
2: it tells the
Dispose(bool)code whether it is currenty in garbage collection (iffalse). When being collected, you shouldn’t touch any other objects outside your own, as they may already be gone. However, if you are being electively disposed (i.e.true) you might want to clean up a few encapsulated managed objects; call.Close()on a connection you are wrapping, for example