Why should Dispose() be non-virtual?

Viewed 6350

I'm new to C#, so apologies if this is an obvious question.

In the MSDN Dispose example, the Dispose method they define is non-virtual. Why is that? It seems odd to me - I'd expect that a child class of an IDisposable that had its own non-managed resources would just override Dispose and call base.Dispose() at the bottom of their own method.

Thanks!

9 Answers

Another, not so obvious reason is to avoid the need to suppress CA1816 warnings for derived classes. These warnings look like this

[CA1816] Change Dispose() to call GC.SuppressFinalize(object). This will prevent derived types that introduce a finalizer from needing to re-implement 'IDisposable' to call it.

Here is an example

class Base : IDisposable
{
    public virtual void Dispose()
    {
        ...

        GC.SuppressFinalize(this);
    } 
}

public class Derived : Base 
{
    public override void Dispose() // <- still warns for CA1816
    {
        base.Dispose();

        ...
    }
}

You can resolve this by just adopting the recommended Dispose pattern.

Related