Typecasting in C#

Casting is usually a matter of telling the compiler that although it only knows that a value is of some general type, you know it’s actually of a more specific type. For example:

object x = "hello";

...

// I know that x really refers to a string
string y = (string) x;

There are various conversion operators. The (typename) expression form can do three different things:

  • An unboxing conversion (e.g. from a boxed integer to int)
  • A user-defined conversion (e.g. casting XAttribute to string)
  • A reference conversion within a type hierarchy (e.g. casting object to string)

All of these may fail at execution time, in which case an exception will be thrown.

The as operator, on the other hand, never throws an exception – instead, the result of the conversion is null if it fails:

object x = new object();
string y = x as string; // Now y is null because x isn't a string

It can be used for unboxing to a nullable value type:

object x = 10; // Boxed int
float? y = x as float?; // Now y has a null value because x isn't a boxed float

There are also implicit conversions, e.g. from int to long:

int x = 10;
long y = x; // Implicit conversion

Does that cover everything you were interested in?

Leave a Comment