Reputation: 783
I expected output C
in this program. But real result is A
.
Please, explain why program prints A
.
class A
{
public virtual void say()
{
Console.WriteLine ("A");
}
}
class B : A
{
public new virtual void say()
{
Console.WriteLine ("B");
}
}
class C : B
{
public override void say()
{
Console.WriteLine ("C");
}
}
class MainClass
{
public static void Main (string[] args)
{
A a = new C ();
a.say();
}
}
Upvotes: 2
Views: 75
Reputation: 14059
It's because you created new virtual method say()
in the class B
.
This new method hides original method A.say()
, so in the class C
you overriden this new method B.say()
but not the A.say()
.
And since you declared your object as A
A a = new C ();
the old A.say()
method is called.
Upvotes: 3
Reputation: 345
You're not overriding the say method in Class B, which is the sub class of Class C.
public new virtual void say()
In the above line, you're hiding the say method. Look at the new modifier here on MSDN
Upvotes: 2