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

var list = new ArrayList();list.Add("Bart");list.Add("John"); ...

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.