I try to use the following code
double d;
double? a = double.TryParse("3.14", out d) ? d : null;
But it won’t compile as “there is no implicit conversion between double and null’. Splitting up the code above as follows works:
double d;
double? a;
if ( double.TryParse("3.14", out d))
a = d;
else
a = null;
How come there is a difference when using the ?-operator ?
The reason is, that you can’t assign
nullto adoubleand your ternary expression returns adouble, not adouble?. Becausenulldoesn’t have an implicit type, the return type of your ternary expression is determined by the part, that has an implicit type, that is the part that returnsd. Asdis adouble, your whole ternary expression evaluates to returning adouble.Fix it by casting either one of the returns to
double?, e.g.