The C# code below:
int? i; i = (true ? null : 0);
gives me the error:
Type of conditional expression cannot
be determined because there is no
implicit conversion between ‘<null>’
and ‘int’
Shouldn’t this be valid? What am i missing here?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The compiler tries to evaluate the right-hand expression. null is null and the 0 is an int literal, not int?. The compiler is trying to tell you that it can’t determine what type the expression should evaluate as. There’s no implicit conversion between null and int, hence the error message.
You need to tell the compiler that the expression should evaluate as an int?. There is an implicit conversion between int? and int, or between null and int?, so either of these should work:
int? x = true ? (int?)null : 0; int? y = true ? null : (int?)0;
Method 2
You need to use the default() keyword rather than null when dealing with ternary operators.
Example:
int? i = (true ? default(int?) : 0);
Alternately, you could just cast the null:
int? i = (true ? (int?)null : 0);
Personally I stick with the default() notation, it’s just a preference, really. But you should ultimately stick to just one specific notation, IMHO.
HTH!
Method 3
The portion (true ? null : 0) becomes a function in a way. This function needs a return type. When the compiler needs to figure out the return type it can’t.
This works:
int? i; i = (true ? null : (int?)0);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0