I know that the general guideline for implementing the dispose pattern warns against implementing a virtual Dispose()
. However, most often we're only working with managed resources inside a class and so the full dispose pattern seems like an overkill - i.e. we don't need a finalizer. In such cases, is it OK to have a virtual Dispose()
in the base class?
Consider this simple example:
abstract class Base : IDisposable
{
private bool disposed = false;
public SecureString Password { get; set; } // SecureString implements IDisposable.
public virtual void Dispose()
{
if (disposed)
return;
if (Password != null)
Password.Dispose();
disposed = true;
}
}
class Sub : Base
{
private bool disposed = false;
public NetworkStream NStream { get; set; } // NetworkStream implements IDisposable.
public override void Dispose()
{
if (disposed)
return;
if (NStream != null)
NStream.Dispose();
disposed = true;
base.Dispose();
}
}
I find this more readable than a complete dispose pattern. I understand that this example would become problematic if we introduced an unmanaged resource into the Base
class. But suppose that this won't happen. Is the above example then valid/safe/robust, or does it pose any problem? Should I stick to the standard full-blown dispose pattern, even if no unmanaged resources are used? Or is the above approach indeed perfectly OK in this situation - which in my experience is far more common than dealing with unmanaged resources?