Today I was faced with the following situation:
I had a base-class which was implementing the IDisposable
pattern (including the GC.SuppressFinalize()
part). From this class, I inherited a sub-class which also required doing some disposing stuff.
Now I asked myself how I should implement the IDisposable
pattern correctly, that the dispose methods were not called twice (and throwing an ObjectDisposedException
) and all my managed objects were disposed properly...
After some Googling around, I found an interesting blog-article:
There it is clearly explained that you only have to override the Dispose(bool disposing)
method (and that you do not require to implement the IDisposable interface
)!
Small Example
You have the following base class:
public class Example : IDisposable
{
private bool _disposed;
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize((object)this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
}
_disposed = true;
}
}
If you now want to inherit a class from the above base-class, you have to implement the sub-class in the following way:
public class SubExample : Example
{
private bool _disposed;
protected override void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
}
_disposed = true;
base.Dispose(disposing);
}
}
That's it! :)
If you have any suggestions or questions, feel free to write a comment! :)
Happy coding!