Why does (int)(object)10m throw “Specified cast is not valid” exception?

A boxed value can only be unboxed to a variable of the exact same type. This seemingly odd restriction is a very important speed optimization that made .NET 1.x feasible before generics were available. You can read more about it in this answer.

You don’t want to jump through the multiple cast hoop, simple value types implement the IConvertible interface. Which you invoke by using the Convert class:

        object o = 12m;
        int ix = Convert.ToInt32(o);

Leave a Comment