Quite confused with the rules of virtual inheritance when i have a method which prevents a derived class from overriding the virtual method defined in the base class. Here is a bit of code to explain my problem better :
using System;
namespace ConsoleApplication1
{
public class A
{
public virtual void DoWork()
{
Console.WriteLine("A.DoWork()");
}
}
public class B : A
{
public override void DoWork()
{
Console.WriteLine("B.DoWork()");
}
}
public class C : B
{
public sealed override void DoWork()
{
Console.WriteLine("C.DoWork()");
}
}
public class D : C
{
public new void DoWork()
{
Console.WriteLine("D.DoWork()");
}
}
public class MyMainClass
{
public static void Main()
{
B b = new D();
b.DoWork();
C c = new D();
c.DoWork();
A a = new D();
a.DoWork();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
}
OUTPUT
C.DoWork()
C.DoWork()
C.DoWork()
Press any key to exit
It's true that if a variable of type B is used to access an instance of C as B b = new C();
b.DoWork()
would result in calling C's implementation of DoWork() since C overrides the virtual DoWork() of A.
But why is it when a variable of type C, B, or A is used to access an instance of D as
B b = new D();
C c = new D();
A a = new D();
a call to DoWork() on each one of them will call the implementation of DoWork() on class C?