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):
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
var list = new ArrayList();list.Add("Bart");list.Add("John"); ...