Cannot assign null to an implicitly-typed variable

后端 未结 4 1618
傲寒
傲寒 2021-01-18 11:22

According to Visual Studio this is not ok:

var foo = null;

But this is ok:

var foo = false ? (double?)null : null;
<         


        
4条回答
  •  滥情空心
    2021-01-18 11:28

    Because compiler cannot predict the type of null. Null can be assigned to any nullable datatype also to any reference type variable. So for implicit conversion, you have to cast null to some specific type.

    var dt = (DateTime?)null; // This is correct
    var dt1 = null; // This will throw compile time error.
    

提交回复
热议问题