Search code examples
c#polymorphism

Can I prevent an inherited virtual method from being overridden in subclasses?


I have some classes layed out like this

class A
{
    public virtual void Render()
    {
    }
}
class B : A
{
    public override void Render()
    {
        // Prepare the object for rendering
        SpecialRender();
        // Do some cleanup
    }

    protected virtual void SpecialRender()
    {
    }
}
class C : B
{
    protected override void SpecialRender()
    {
        // Do some cool stuff
    }
}

Is it possible to prevent the C class from overriding the Render method, without breaking the following code?

A obj = new C();
obj.Render();       // calls B.Render -> c.SpecialRender

Solution

  • You can seal individual methods to prevent them from being overridable:

    public sealed override void Render()
    {
        // Prepare the object for rendering        
        SpecialRender();
        // Do some cleanup    
    }