Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

c# - Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and <null>

Why does this not compile?

int? number = true ? 5 : null;

Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and <null>

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The spec (§7.14) says that for conditional expression b ? x : y, there are three possibilities, either x and y both have a type and certain good conditions are met, 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 conversions are possible, which we will get into the details of below.

Now, let's turn to the germane part of the spec:

If only one of x and y has a type, and both x and y are implicitly convertible to that type, then that is the type of the conditional expression.

The issue 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 does not have a type and null is not implicitly convertible to an int1. Therefore, "certain good conditions" aren't met, and a compile-time error occurs.

There are two ways around this:

int? number = true ? (int?)5 : null;

Here we are still in the case where only one of x and y has a type. Note that null still does not have a type yet the compiler won't have any problem with this because (int?)5 and null are both implicitly convertible to int? (§6.1.4 and §6.1.5).

The other way is obviously:

int? number = true ? 5 : (int?)null;

but now we have to read a different clause in the spec to understand why this is okay:

If x has type X and y has type Y then

  • If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.

  • If an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.

  • Otherwise, no expression type can be determined, and a compile-time error occurs.

Here x is of type int and y is of type int?. There is no implicit conversion from int? to int, but there is an implicit conversion from int to int? so the type of the expression is int?.

1: Note further that the type of the left-hand side is ignored in determining the type of the conditional expression, a common source of confusion here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...