Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How Dynamic Binding (with hiding) works?

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading