I've read through a few tutorials (including the ones on the MSDN website) about Method Hiding and Overriding in C# and I ran across a problem in a snippet of code I wrote while trying to understand the logic:
class A
{
public virtual void Foo()
{
Console.WriteLine("A");
}
}
class B : A
{
public override void Foo()
{
Console.WriteLine("B");
}
}
class C : B
{
new public virtual void Foo()
{
Console.WriteLine("C");
}
}
class Driver
{
static void Main()
{
A a = new A();
a.Foo();
B b = new B();
b.Foo();
C c = new C();
c.Foo();
a = new B();
a.Foo();
a = new C();
a.Foo();
Console.ReadKey();
}
}
Whenever I run that code I get this output: A B C B B
I understand the first four, but shouldn't the fifth output be 'C' because the run-time instance is C and not A? I'm not very comfortable yet with method hiding but shouldn't declaring "new public virtual void Foo()" in class C allow that Foo() to be called instead of the one from B?