views:

1238

answers:

6

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
+11  A: 

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    
}
Matt Hamilton
A: 

In B, do

protected override sealed void Render() { ... }
Matt Bishop
A: 

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

Scott Wisniewski
+1  A: 

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()
    {
    }
}
Ian Nelson
A: 

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.

James A. Rosen
+1  A: 

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 
 //{
 //}
}
bitbonk