Question

The following code leads to an InvalidCastException.

  object x = (short) 1;
  int y = (int) x;

I know that I could cast x first to a short and then to an int, although that is not an option, as the type of the boxed value is not known (but it is definetly smaller than an int).

How can I work around the exception when unboxing to a type, that is larger than the boxed type?

Edit: I solved my problem by using the dynamic type (with all the performance implications)

Was it helpful?

Solution

You can only unbox an object to its exact type.

Instead, you should call Convert.ToInt32(), which will work with any numeric type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top