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.
source share