The output of this code block does not make sense to me

The execution type of all calling instances is D, so all calls to F () must be the F () method declared in D.

using System; class A { public virtual void F() { Console.WriteLine("AF"); } } class B: A { public override void F() { Console.WriteLine("BF"); } } class C: B { new public virtual void F() { Console.WriteLine("CF"); } } class D: C { public override void F() { Console.WriteLine("DF"); } } class Test { static void Main() { D d = new D(); A a = d; B b = d; C c = d; aF(); bF(); cF(); dF(); } } 

output:

 BF BF DF DF 

There should be no way out:

 DF DF DF DF 
+8
c # virtual-functions
source share
3 answers

Versions Using Overrides and New Keywords (C # Programming Guide)

If a new keyword is preceded by a method in a derived class, the method is defined as a class independent of the method in the database.

So, you'r F methods from A and B not related to them from C and D , and therefore you get what you get.

At runtime, the CLR looks for an implementation of the virtual method that should be used, starting with the type that is declared by the variables so that their type really is. For aF() and bF() it stops at declaring bF() , because CF() is a different method (due to new ).

+7
source share

You are using new public virtual void F() in class C: B. This means that F() in class C and F() in class B is a different method.

Therefore, when you redefine C to class D , the F() method in class D overwritten from class C , not B

Another obvious example might be the following:

  C c = new C(); B b = c; bF(); cF(); 
+1
source share

It should not ...

 A a = d; 

This means that you are creating a class of type A And since you explicitly override the associated method in class B ; A uses a method in class B

On the other hand, in this line

 new public virtual void F() { Console.WriteLine("CF"); } 

You declare that you will not use the F() method from the database using the new keyword.

If you redefined the F() method in classes D and C , all instances would call the F() method declared in class D

+1
source share

All Articles