Home > Software design >  How Dynamic Binding (with hiding) works?
How Dynamic Binding (with hiding) works?

Time:04-29

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" !!

CodePudding user response:

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 call a.WhoAreYou() with the static type of A resolves to B because public override void WhoAreYou() in B overrides the implementation of A, but does not get overriden further.

If you where to do

C c = new D();
c.WhoAreYou(); // "I am a D" !!

this would resolve to D. In this case, the methods WhoAreYou of 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.

  • Related