Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Overriding a base class method more than one derived class down inheritance chain

I have an inheritance chain that consists of three classes A,B, and C, where A and B are abstract, and C is a concrete implementation of B.

I have a virtual method on the base abstract class A, Foo() that I would like to override in the concrete class C.

If I try and override just in Class C it is never picked up and always uses the default base class implementation, but if I override in both B & C, it only ever uses the B.Foo() implementation of the virtual method.

Do I have to declare something extra on B.Foo() other than 'override'?

Obviously these are simplified versions of my classes, but here are my method declarations:

abstract class A {
  protected virtual string Foo() {
    return "A";
  }
}

abstract class B : A {
  protected override string Foo() {
    return "B";
  }
}

class C : B {
  protected override string Foo() {
    return "C";
  }
}
like image 228
theringostarrs Avatar asked Nov 06 '22 06:11

theringostarrs


1 Answers

Huh?

void Main()
{
    new C().DumpFoo(); // C
    A x=new C();
    x.BaseDumpFoo(); //C
}

abstract class A {
  protected virtual string Foo() {
    return "A";
  }
  public void BaseDumpFoo()
  {
    Console.WriteLine(Foo());
  }
}

abstract class B : A {
  protected override string Foo() {
    return "B";
  }
}

class C : B {
  protected override string Foo() {
    return "C";
  }
  public void DumpFoo()
  {
    Console.WriteLine(Foo());
  }
}

Output is C. Remove Foo implementation from B and the output is still C

like image 145
spender Avatar answered Nov 12 '22 11:11

spender