#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.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: