4

I have got the following class structure, and have plenty of classes like C derived from B, in some of the classes I dont want by B.OnShow() but I want A.OnShow() to be executed from C Any tricks?

abstract class A
{
   protected virtual void OnShow()
   {
        //some code
        base.OnShow();
   }
}

class B : A
{
    protected override void OnShow()
    {
      //some other code
      base.OnShow();
    }
}

class C : B
{
   protected override void OnShow()
   {
      //some other code
      base.OnShow();
   }
}
Jobi Joy
  • 49,102
  • 20
  • 108
  • 119
  • possible duplicate of [How to call a second-level base class method like base.base.GetHashCode()](http://stackoverflow.com/questions/1006530/how-to-call-a-second-level-base-class-method-like-base-base-gethashcode) – nawfal May 02 '14 at 16:09

3 Answers3

5

Don't have C extend from B, instead make a new class "X" that extends from A and has the parts that are currently in B that you want for both B and C and then have C and B extend from "X". Then B will just have the bits in it that you want for B specifically (a bit abstract, but I think that makes sense).

Generally speaking, if you are trying to skip a parent method then you are doing something wrong.

TofuBeer
  • 60,850
  • 18
  • 118
  • 163
2

Eric Lippert has already answered a very similar question and basically stated that it's not permitted in C#.

Community
  • 1
  • 1
Rob
  • 45,296
  • 24
  • 122
  • 150
2

It sounds like a design problem here. If C really is a B, it should probably do everything B needs to do in the OnShow. If not, you should probably be utilizing something other than direct inheritance, or something other than a single virtual function call.

If you really really wanted to, you could have:

abstract class A
{
    protected virtual void OnShow()
    {
        UniqueOnShowStuff();
        base.OnShow();
    }
    protected virtual void UniqueOnShowStuff()
    {
     //
    }
}

class B : A
{
    protected override void OnShow()
    {
        // Things all B's need to Show
        base.OnShow();
    }
    protected override void UniqueOnShowStuff()
    {
        // Things most B's might want to show but don't have to
    }
}

class C : B
{
    protected override void OnShow()
    {
        // Things all C's need to show
        base.OnShow();
    }
    protected override void UniqueOnShowStuff()
    {
        // override without a base call so you don't show B's things
    }
}

This is a horrible pattern though, and I wouldn't recommend it if you could come up with a better way to redesign the objects/functionality.

Tanzelax
  • 5,406
  • 2
  • 25
  • 28