Why doesn't this C# code compile?

后端 未结 4 1277
离开以前
离开以前 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

    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
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-11 16:34
    double? test = true ? (double?)null : 1.0;
    

    will work. That's because there is no conversion from the type of the first expression (null) to the type of the second expression (double).

    0 讨论(0)
  • 2020-12-11 16:43

    The left hand side of the assignment is not used when deducing the type of an ?: expression.

    In b ? A : B, the types of A and B must either be the same, or one must be implicitly convertible to the other.

    0 讨论(0)
提交回复
热议问题