I ran with strangeness:
var k = (decimal?)(int?)1; //valid cast
var p = (decimal?)(int?)(object)(int?)1; //valid cast
var l = (decimal?)(object)(int?)1; //Specified cast is not valid
Can someone explain why this happens?
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.
The first cast is:
inttoint?int?todecimal?Both conversions are valid.
The second case is:
inttoint?int?(which ends up as a boxedint)int?int?todecimal?All of these conversions are valid.
The third case is:
inttoint?int?(which ends up as a boxedint)decimal?The last conversion here is invalid – you can only unbox to the same value type or its nullable equivalent. (Actually the CLR is somewhat more forgiving than this, but that’s not relevant in this case.)
The conversion to
int?in each case is actually irrelevant. The unboxing to a nullable type is somewhat irrelevant too, in that unboxing to a nullable type is like unboxing to a non-nullable type, except that a null reference is unboxed to a null value. Given that there are no null values here, your final example is equivalent to: