#221 – When Unboxing, You Must Match the Original Type Exactly

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.

            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.

            int i = 1964;
            object o = i;    // box

            // Attempted unbox to different type
            // Throws InvalidCastException
            uint ui = (uint)o;

This cast, as part of the unboxing operation, is allowed at compile time, but throws an InvalidCastException at run-time.

Advertisement