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"); }
}
C c = new D();
c.WhoAreYou();// "I am a D"
A a = new D();
a.WhoAreYou();// "I am a B" !!!!
How the reference is allocated internally,reference A contains the reference of B? Can any one explain Whats going On?
In class
C
, the methodWhoAreYou()
doesn't override the base class method, as it is defined withnew
keyword which adds a new method with the same name which hides the base class method. That is why this:invokes the overridden method in
D
which overrides its base class method defined withnew
keyword.However, when the target type is
A
, then this:invokes the overridden method in
B
, as you're calling the method ona
of typeA
whose method is overriden byB
.