Why this explicit cast does throw Specified cast is not valid. exception ?
decimal d = 10m;
object o = d;
int x = (int)o;
But this works:
int x = (int)(decimal)o;
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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: