O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

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

Cast Expressions

Cast expressions are a way to carry out explicit conversions at runtime. In essence, you’re telling the compiler you know more about the type of an object than it can possibly know. Don’t worry; the compiler is hardened against this type of insult.

The syntax for a cast expression looks like this (where type is the name of a type):

(type) unary-expression

An example where this is used on a regular basis is while dealing with a weakly typed application programming interface (API). To be maximally applicable, some APIs use the root of the type hierarchy, System.Object, to deal with any kind of object imaginable. A good example can be found in the old, nongeneric collection types in the System.Collections namespace:

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