开发者

Why can't I set a nullable int to null in a ternary if statement? [duplicate]

开发者 https://www.devze.com 2022-12-28 22:22 出处:网络
This question already has answers here: Conditional operator cannot cast implicitly? (3 answers) Closed 9 years ago.
This question already has answers here: Conditional operator cannot cast implicitly? (3 answers) Closed 9 years ago.

The C# code below:

int? i;
i = (true ? null : 0);

gives me the error:

Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'int'开发者_如何学Go

Shouldn't this be valid? What am i missing here?


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;


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!


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);
0

精彩评论

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