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:

Get C# 5.0 Unleashed now with O’Reilly online learning.

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