C# IDisposable Pattern on Sub-classes





0/5 (0 vote)
C# IDisposable pattern on sub-classes
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:
/// <summary>
/// <see cref="IDisposable" /> interface example.
/// </summary>
public class Example : IDisposable
{
/// <summary>
/// Flag stating if the current instance is already disposed.
/// </summary>
private bool _disposed;
/// <summary>
/// The <see cref="IDisposable" /> implementation.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize((object)this);
}
/// <summary>
/// Dispose method, releasing all managed resources.
/// </summary>
/// <param name="disposing">States if the resources should be disposed.</param>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
// Dispose all managed resources here.
}
_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:
/// <summary>
/// SubClass of a <see cref="IDisposable" /> implementing base-class.
/// </summary>
public class SubExample : Example
{
/// <summary>
/// Flag stating if the current instance is already disposed.
/// </summary>
private bool _disposed;
/// <summary>
/// Dispose method override, releasing all managed resources of the sub-class.
/// </summary>
/// <param name="disposing">States
/// if the resources should be disposed.</param>
protected override void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
// Dispose all managed resources here.
}
_disposed = true;
base.Dispose(disposing);
}
}
That's it! :)
If you have any suggestions or questions, feel free to write a comment! :)
Happy coding!