Cannot assign null to an implicitly-typed variable

后端 未结 4 1617
傲寒
傲寒 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

    The second example has double? type and the compiler knows it. According to documentation

    It is important to understand that the var keyword does not mean "variant" and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.

    The compiler should ensure the type match with var.

    var foo = null;
    

    The compiler can't identify the type of foo.

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

    Now the foo has double? type.

提交回复
热议问题