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
328 views
in Technique[技术] by (71.8m points)

.net - Why doesn't this C# code compile?

double? test = true ? null : 1.0;

In my book, this is the same as

if (true) {
  test = null;
} else {
  test = 1.0;
}

But the first line gives this compiler error:

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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This happens because the compiler tries to evaluate the statement from right to left. This means that it sees 1.0 and it decides it is double (not double?) and then it sees null.

So there is clearly no implicit conversion between double and null (in fact there is no implicit conversion between Struct and null).

What you can do is explicitly tell the compiler that one of the two expressions that are convertible to each other.

double? test = true ? null : (double?) 1.0;    // 1
double? test = true ? (double?)null : 1.0;     // 2
double? test = true ?  default(double?) : 1.0; // 3
double? test = true ? new double?() : 1.0;     // 4

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

...