The main reason is that in C # the explicit casting operator has two different meanings:
- A value that preserves the view: "I know that this object is always of type T, although the compiler could not prove it statically - please let me use it as T instead of something more general."
- Value that changes the view: "I know that this object is not of type T, but there is a transformation to turn it into T, and I would like this conversion to be performed."
So, the reason you get two different behaviors is because you use each of the above values:
- Your first snippet says, "I know that this
object definitely an Int16 box, and I would like to use it as such." But since this is actually an Int32 box, you get a type mismatch exception. - Your second snippet says, "I know that this
Int32 definitely not Int16 , but I would like to convert it to one."
In other words, unboxing only works if you are trying to unpack the original type. According to Eric Lippert , the reason is that it was simply too impractical to implement it in such a way that it could be unpacked and converted in one operation.
source share