Why doesn't this C# code compile?

后端 未结 4 1281
离开以前
离开以前 2020-12-11 16:23
double? test = true ? null : 1.0;

In my book, this is the same as

if (true) {
  test = null;
} else {
  test = 1.0;
}
4条回答
  •  感情败类
    2020-12-11 16:24

    Because the compiler can't figure out that for null and 1.0 to be compatible, the values need to be cast to double?. This needs to be explicitly stated.

    double? test = true ? (double?) null : 1.0;
    

提交回复
热议问题