2

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?

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
zach
  • 29
  • 2
  • 2
    I don't think you can use `new` and `virtual` at the same time. `virtual` means you're overriding; `new` means you are shadowing. – Robert Harvey Jun 23 '14 at 19:49
  • @RobertHarvey I didn't think so, either; maybe it just gives a warning? Though to Zach; that's what hiding does, essentially. – Andrew Barber Jun 23 '14 at 19:49
  • You have read about method overriding and hiding. The last case is hiding. Doesn't that make sense? – usr Jun 23 '14 at 19:50
  • @RobertHarvey, its `new` and `override`, that can't be used together, `new` and `virtual` can be used together – Habib Jun 23 '14 at 19:50
  • So `new` `virtual` means that you are shadowing, but you can override the shadowed method later? Sounds confusing to me, and I've never seen anyone actually do this. – Robert Harvey Jun 23 '14 at 19:51
  • 1
    Please reopen if this duplicate question does not answer yours. I think it does. – usr Jun 23 '14 at 19:51
  • @RobertHarvey, http://stackoverflow.com/questions/10415900/what-is-public-new-virtual-void-method-mean and yes it is weird. – Habib Jun 23 '14 at 20:01
  • Thanks usr, the duplicate question answered my question perfectly. – zach Jun 23 '14 at 20:02

1 Answers1

3

Fifth output is B, because you're looking at C instance as if it was A instance, so that's where you're method dispatch begin.

From A.Foo it goes up the inheritance chain, checks B.Foo and C.Foo. Because C.Foo is marked with new modifier, B.Foo is the one that is actually called.

You'd get C as output for following snippet:

C c = new C();
c.Foo();
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263