Why can't I set a nullable int to null in a ternary if statement? [duplicate]
Solution 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;
Solution 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!
Solution 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);