We know that we can do explicit casts when assigning from one type to another and the assignment will work if the value being assigned can be represented by the target type.
1
2
| int i = 1964;uint ui = (uint)i; // cast works fine |
But when casting as part of an unboxing operation, the target type must match the original type exactly.
1
2
3
4
5
6
| int i = 1964;object o = i; // box// Attempted unbox to different type// Throws InvalidCastExceptionuint ui = (uint)o; |
This cast, as part of the unboxing operation, is allowed at compile time, but throws an InvalidCastException at run-time.

