C # 6 error? virtual new method of strange behavior

I have this code:

using System; namespace Test { class Program { static void Main(string[] args) { Foo foo = new Foo(); Bar bar = new Bar(); Baz baz = new Baz(); Foo fooBar = new Bar(); Foo fooBaz = new Baz(); Bar barBaz = new Baz(); foo.Test(); bar.Test(); baz.Test(); fooBar.Test(); fooBaz.Test(); barBaz.Test(); Console.ReadLine(); } } internal class Foo { public virtual void Test() { Console.WriteLine("Foo"); } } internal class Bar : Foo { public new virtual void Test() { Console.WriteLine("Bar"); } } internal class Baz : Bar { public override void Test() { Console.WriteLine("Baz"); } } } 

he deduces me:

 Foo Bar Baz Foo Foo Baz 

But I thought it should be:

 Foo Bar Baz Foo Baz Baz 

Because Baz redefines the method. What's going on here? Am I missing something? Why was the result for fooBaz.Test () "Foo" instead of "Baz"?

+7
c #
source share
2 answers

Buz overrides the method, therefore

 Bar barBaz = new Baz(); barBaz.Test(); 

will print Baz .

But Bar does not override - it hides the basic Test method and makes the new method virtual. Then Baz overrides the new method from Bar , not the method from Foo . Therefore, if you refer to it as follows: Foo fooBaz = new Baz(); , then fooBaz treated as an instance of Foo , which has no idea about the hide method.

The result you expect will be generated if you change public new virtual void Test() to public override void Test() .

See also the following sections:

+5
source share

When you use the new keyword on Bar.Test , you say that it is not related to Foo.Test , except that it has the same name. Since Baz inherits from Bar, it overrides Bar.Test , but leaves Foo.Test unmodified.

When you call fooBaz.Test , it scans the unmodified Foo.Test method and prints "Foo".

When you call barBaz.Test , it looks at the override method of Bar.Test and prints "Baz".

+2
source share

All Articles