Zoo tutorials: [ SQL | Linux | XML ]
ProgZoo: [ Java | C# | VB | C++ | Perl ]
Log in

A Gentle Introduction to
C# Programming

Casting

 

Data types

Casting

We sometimes need to cast from one class to another. We can only cast up or down the class hierarchy. As Object is at the top of the class hierarchy we can always cast to an object.

Casting down the hierarchy may result in a run time error.

1. [ C# ] casting


Big

The sample code shows Point p being cast to an Object then cast again back to a Point.

2. [ C# ] Incorrect casting


Big

There is a danger of casting to incompatable type. When this happens we get a run time error.

The code shown compiles OK but fails at run time.

3. [ C# ] Test before casting


Big

We can check to see if the cast is going to work using is.