New keyword: why is the derived method not called?

I have three simple classes:

class A { public virtual void Write() { Console.Write("A"); } } class B:A { public override void Write() { Console.Write("B"); } } class C : B { public new void Write() { Console.Write("C"); } } 

And I create objects and calling their methods:

 A a = new A(); a.Write(); A b = new C(); b.Write(); C c = new C(); c.Write(); 

And the conclusion will be: ABC

What I cannot understand is why this code creates B ? :

 A b = new C(); b.Write(); 

I thought it should be C However, I have tested many times and it is always B

I understand that A b = new C() creates a new type of object C. Thus, the output must be C. Or is it a special behavior to call an overridden method when we use it without casting?

Why is this happening? Since we did not use references to class B

+5
source share
1 answer

This will work if you use ((C)b).Write();

With the new keyword, you are not overriding the Write method for C, but rather creating a new method defined only for C. So, for your C, you actually have 2 methods with the name of the Write method.

 A c = new C(); c.Write(); //Output "B", you're calling the overridden method ((C)c).Write(); //Output "C", you're calling the method defined on C //or (c as C).Write(); 

The same thing happens when you define c as C :

 C c = new C(); c.Write(); //Output "C" ((A)c).Write(); //Output "B" 

In the first example, you call the new method defined on C. In the second line, you call the Write method from A, which is overridden by B, hence the output is "B" .

Edit: (some more explanation)

The variable C is of type A, so your compiler knows that "c is an instance of A", it is not known that it actually has a more derived type. When you call the Write method on it, it will call the method defined on A (which is overridden by B). Your base class A does not know your new method defined in C (which makes new creates a new method), so if you do not pass it to C so that the compiler knows about the actual derived type of C , the method of your base class is called.

+6
source

Source: https://habr.com/ru/post/1243848/


All Articles