c# - Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and <null> -
why not compile?
int? number = true ? 5 : null;
type of conditional expression cannot determined because there no implicit conversion between 'int' , <null>
the spec (§7.14) says conditional expression b ? x : y
, there 3 possibilities, either x
, y
both have type and good conditions met, 1 of x
, y
has type and good conditions met, or compile-time error occurs. here, "certain conditions" means conversions possible, details of below.
now, let's turn germane part of spec:
if 1 of
x
,y
has type, , bothx
,y
implicitly convertible type, type of conditional expression.
the issue here in
int? number = true ? 5 : null;
only 1 of conditional results has type. here x
int
literal, , y
null
not have type and null
not implicitly convertible int
1. therefore, "certain conditions" aren't met, , compile-time error occurs.
there are 2 ways around this:
int? number = true ? (int?)5 : null;
here still in case 1 of x
, y
has type. note null
still not have type yet compiler won't have problem because (int?)5
, null
both implicitly convertible int?
(§6.1.4 , §6.1.5).
the other way obviously:
int? number = true ? 5 : (int?)null;
but have read different clause in spec understand why okay:
if
x
has typex
,y
has typey
then
if implicit conversion (§6.1) exists
x
y
, noty
x
,y
type of conditional expression.if implicit conversion (§6.1) exists
y
x
, notx
y
,x
type of conditional expression.otherwise, no expression type can determined, , compile-time error occurs.
here x
of type int
, y
of type int?
. there no implicit conversion int?
int
, there implicit conversion int
int?
type of expression int?
.
1: note further type of left-hand side ignored in determining type of conditional expression, common source of confusion here.
Comments
Post a Comment