O'Reilly logo

C# Primer Plus by Klaus Michelsen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required