9

Suppose there is base class A and derived class B.

Class A has two functions: fun1() and fun2(), where fun1() calls fun2().

Class B overrides fun1() and fun2(), and again fun1() calls fun2().

However, I'd like to call base.fun1() in overriden fun2(). Since base.fun1() calls fun2() instead of the base class' version that creates quite unfortunate loop:

fun1() -> fun2() -> base.fun1() -> fun2() -> base.fun1() -> ...

Is there any way to force base.fun1() to call base version of fun2()? I am aware that the real problem probably lies in bad design of those classes, but I'm still curious if it's somehow possible.

Maras
  • 982
  • 9
  • 15
  • Those functions do some different stuff aside from calling each other that are not really important in this question. I'm not looking for help with very specific code that can probably be rewritten in many better ways. In this example I'd see it this way: `fun1() -> fun2() -> base.fun1() -> base.fun2()`. Unfortunately, after overriding `base.fun2()`, the `base.fun1()` calls `fun2()` instead. – Maras Mar 07 '20 at 19:00

1 Answers1

5

Use method hiding.

Method hiding is also known as shadowing. The method of the parent class is available to the child class without using the override keyword in shadowing. The child class has its own version of the same function. Use the new keyword to perform shadowing.

public class A
{
    public virtual void Func1() { Func2(); }

    public virtual void Func2() { Console.WriteLine("A: Func2"); }
}

public class B : A
{
    public override void Func1() { Func2(); }

    public new void Func2() { base.Func1(); }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
jasonvuriker
  • 255
  • 1
  • 12
  • 4
    @Maras: Two things (1) you might want to make `Func2` not virtual in `A`, and (2) use extreme caution with this pattern. It can be very confusing to users who naively expect virtual dispatch to get static dispatch. – Eric Lippert Mar 07 '20 at 23:38