Question

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
Was it helpful?

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    
}

OTHER TIPS

Yes, you can use the sealed keyword in the B class's implementation of Render:

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

    protected virtual void SpecialRender()
    {
    }
}

In B, do

protected override sealed void Render() { ... }

try sealed

class B : A
{
  protected sealed override void SpecialRender()
  {
    // do stuff
  }
}

class C : B
  protected override void SpecialRender()
  {
    // not valid
  }
}

Of course, I think C can get around it by being new.

yes. If you mark a method as Sealed then it can not be overriden in a derived class.

An other (better ?) way is probablby using the new keyword to prevent a particular virtual method from being overiden:

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 B2 : B
{
    public new void Render()
    {
    }
}
class C : B2
{
    protected override void SpecialRender()
    {
    }
    //public override void Render() // compiler error 
    //{
    //}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top