I have been practicing Dynamic Binding (with hiding) and i came across a code block like below.
The output of the program is:
"I am a B"
And I just couldn't understand it.
Can anyone can explain it to me? Thanks in advance.
class A
{
public virtual void WhoAreYou() { Console.WriteLine("I am an A"); }
}
class B : A
{
public override void WhoAreYou() { Console.WriteLine("I am a B"); }
}
class C : B
{
public new virtual void WhoAreYou() { Console.WriteLine("I am a C"); }
}
class D : C
{
public override void WhoAreYou() { Console.WriteLine("I am a D"); }
}
A a = new D();
a.WhoAreYou(); // "I am a B" !!
The "trick" here is in this line:
public **new** virtual void WhoAreYou(). This creates a new virtual member in class C, instead of overriding the base implementation. Therefore, the virtual calla.WhoAreYou()with the static type of A resolves to B becausepublic override void WhoAreYou()in B overrides the implementation of A, but does not get overriden further.If you where to do
this would resolve to D. In this case, the methods
WhoAreYouof C/D and of A/B are completely distinct and the effect would be the same if they had entirely different names.This is a very rare scenario, I have actually not seen any commonly used APIs that use the concept to declare a method
new virtual, because it's confusing.