开发者

Assignment of "double?" using "?" operator not possible?

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 n开发者_StackOverflow社区o 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 null to a double and your ternary expression returns a double, not a double?. Because null doesn'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 returns d. As d is a double, your whole ternary expression evaluates to returning a double.

Fix it by casting either one of the returns to double?, e.g.

double d;
double? a = double.TryParse("3.14", out d) ? (double?)d : null;


You could cast null to double? on the right hand side of the null coalescing operator to indicate to the compiler the desired return type:

double? a = double.TryParse("3.14", out d) ? d : (double?)null;


The following should work, where you explicitly cast the null

double? a = double.TryParse("3.14", out d) ? d : (double?)null;


It's because the null has to be castable to the type of d (double in this case) as well as the type of a


You have to cast d to double?.

Try a = double.TryParse("3.14", out d) ? (double?) d : null;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜