New keyword: why is the derived method not called?

It would work if you'd use ((C)b).Write();

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

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 happens when you would define c as C:

C c = new C();

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

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

Edit: (some more explanation)

Variable c is of type A, so that's what your compiler knows "c is an instance of A", it is not known that it is actually of a more derived type. When you call the method Write on it, it will invoke the method defined on A (which is overriden by B). Your base class A has no knowledge of your new method defined on C (that's what new does, create a new method), so unless you cast it to C to let the compiler know about the actual, derived type of c, the method of your base class will be called.

Tags:

C#

Inheritance