Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Run-Time Type Information and Casts

Consider the following declarations which make use of the Rectangle and Square classes defined in Programs gif and gif:

Rectangle r = new Rectangle(new Point(0,0), 5, 10);
Square s = new Square(new Point(0,0), 15);
Clearly, the assignment
r = s;
is valid because Square is derived from Rectangle. That is, since a Square is a Rectangle, we may assign s to r.

On the other hand, the assignment

s = r; // Wrong.
is not valid because a Rectangle instance is not necessarily a Square.

Consider now the following declarations:

Rectangle r = new Square(new Point(0,0), 20);
Square s;
The assignment s=r is still invalid because r is a Rectangle, and a Rectangle is not necessarily a Square, despite the fact that in this case it actually is!

In order to do the assignment, it is necessary to convert the type of r from a Rectangle to a Square. This is done in C# using a cast operator :

s = (Square)r;
The C# common language runtime checks at run-time that r actually does refer to a Square and if it does not, the operation throws a ClassCastException. (Exceptions are discussed in Section gif).

To determine the type of the object to which r refers, we must make use of run-time type information  . In C# the is operator  can be used to test whether a particular object is an instance of some class. Thus, we can determine the class of an object like this:

if (r is Square)
    s = (Square)r;
This code does not throw an exception because the cast operation is only attempted when r actually is a Square.

Alternatively, we may use the as operator  to do the conversion like this:

 
s = r as Square;
The as operator returns null (and does not throw an exception) if the object to which r refers is not a Square.


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.