2

I have a method Hello in class A, which should be overridden by class B. Therefore the overridden method in B has to call the base method to prepare something.

The method DoSomeThing is the additional functionality of this method. Now I want to override B.Hello in the new class C in order to change logic of B.DoSomeThing.

Requirements:

  • C.Hello needs the method call of A.Hello, too, in order to do some basic preparations
  • Only B.DoSomeThing should be replaced width new functionality, defined in C.DoSomeThing2
  • I am not allowed to change code inside A and B
public class A 
{
   protected virtual void Hello() {}
}

public class B : A 
{
   protected override void Hello() {
      base.Hello();

      DoSomeThing();
   }
}

public class C : B 
{
   protected override void Hello() {
      ???????????????

      DoSomeThing2();
   }
}

I cannot call the base method of class A. What would be the best solution for my problem?

Simply copy and paste the code of A.Hello wouldn't work because of private methods in A.

EDIT: class C has to inherit from class B.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
D.Weder
  • 187
  • 1
  • 7
  • Can you not inherit from class A directly and after calling the base method, write your own logic of DoSomething? – Kunal Khivensara Oct 12 '20 at 11:26
  • I have to inherit from B, because I need the methods and logic. – D.Weder Oct 12 '20 at 11:33
  • So you need all the functionality of A, partial functionality of B and some new functionality of C without touching the class B, seems impossible to me. – Kunal Khivensara Oct 12 '20 at 11:36
  • 8
    Sounds like your inheritance tree is broken. Try to refactor to Composition over Inheritance. As is, your requirements contradict each other, given that C _must_ inherit B, not A. – Fildor Oct 12 '20 at 11:39
  • One way to do this is using reflection. However this is neither good style, nor performant. See Evk's answer to this question: https://stackoverflow.com/questions/2323401/how-to-call-base-base-method – Döharrrck Oct 12 '20 at 11:55
  • Does this answer your question? [How to call base.base.method()?](https://stackoverflow.com/questions/2323401/how-to-call-base-base-method) – V0ldek Oct 12 '20 at 12:04
  • 2
    @Đøharrrck When you made a mess, you clean it up, don't make it worse. – Fildor Oct 12 '20 at 12:06
  • Right, that's why I wrote that this isn't good style. However, it is technically a possible solution for the question, especially if the author of class C doesn't have control over the source code of classes A and B and cannot clean up. – Döharrrck Oct 12 '20 at 12:37

0 Answers0