Losing and Regaining Type Information

If we assign an object of a derived class (Rectangle) to a variable of type base class (Shape) as in the following:

Shape myShape = new Rectangle();

the Rectangle object looses part of its identity. It is impossible to tell by looking at myShape in the source code whether it references an object of type Rectangle, Circle, or Triangle; we only know it's a Shape.

Even if we happen to know that myShape contains a Rectangle object in a particular place in our code and want to access its Height property (assuming that Rectangle contains a Height property) with the following call:

myShape.Height = 20.4;     //Invalid

the compiler returns an error message, because it cannot determine at compile time whether myShape ...

Get C# Primer Plus now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.