The conditional expression type cannot be determined because there is no implicit conversion between 'int' and <null>
Why is this not compiling?
int? number = true ? 5 : null; The conditional expression type cannot be determined because there is no implicit conversion between 'int' and <null>
The specification (§7.14) says that for the conditional expression b ? x : y b ? x : y there are three possibilities: either x and y both have a type and some good conditions are satisfied, only one of x and y has a type and certain good conditions are met, or a compile-time error occurs. Here, “certain good conditions” means certain transformations, which we will discuss below.
Now let's move on to the Germanic part of the specification:
If only one of
xandyis of type, and bothxandyimplicitly converted to this type, then this is a conditional expression type.
The problem here is that in
int? number = true ? 5 : null; only one of the conditional results has a type. Here x is an int literal, and y is null , which is not of type , and null implicitly converted to int 1 . Therefore, “certain good conditions” are not fulfilled, and a compile-time error occurs.
There are two ways:
int? number = true ? (int?)5 : null; Here we are still in the case where only one of x and y is of type. Note that null still has no type, but the compiler will not have any problems with this, because (int?)5 and null both implicitly converted to int? (§6.1.4 and §6.1.5).
Another way, obviously, is:
int? number = true ? 5 : (int?)null; but now we have to read another sentence in the specification to understand why this is normal:
If
xis of typexandyis of typey, then
If an implicit conversion (§6.1) exists from
xtoy, but not fromytox, thenyis a conditional expression type.If an implicit conversion (§6.1) exists from
ytox, but not fromxtoy, thenxis a conditional expression type.Otherwise, the type of expression cannot be determined, and a compile-time error occurs.
Here, x is of type int and y is of type int? . No implicit conversion from int? to int , but is there an implicit conversion from int to int? , so the expression type is int? .
1 : Note that the type of the left side is ignored when determining the type of conditional expression, which is a common source of confusion.
null has no identifiable type - it just needs a little nudge to make it happy:
int? number = true ? 5 : (int?)null;