I have an abstract class that implements IDisposable, like so:
public abstract class ConnectionAccessor : IDisposable
{
public abstract void Dispose();
}
In Visual Studio 2008 Team System, I ran Code Analysis on my project and one of the warnings that came up was the following:
Microsoft.Design : Modify 'ConnectionAccessor.Dispose()' so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance ('this' or 'Me' in Visual Basic), and then returns.
Is it just being silly, telling me to modify the body of an abstract method, or should I do something further in any derived instance of Dispose
?
While it does seem a little like nit-picking, the advice is valid. You are already indicating that you expect any sub-types of ConnectionAccessor will have something that they need to dispose. Therefore, it does seem better to ensure that the proper cleanup is done (in terms of the GC.SuppressFinalize call) by the base class rather than relying on each subtype to do it.
I use the dispose pattern mentioned in Bruce Wagners book Effective C# which is basically:
public class BaseClass : IDisposable
{
private bool _disposed = false;
~BaseClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(true);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
//release managed resources
}
//release unmanaged resources
_disposed = true;
}
}
public void Derived : BaseClass
{
private bool _disposed = false;
protected override void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
//release managed resources
}
//release unmanaged resources
base.Dispose(disposing);
_disposed = true;
}
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