Cannot assign null to an implicitly-typed variable

后端 未结 4 1609
傲寒
傲寒 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:43

    Implicitly typed variable declaration/assignment serves two purposes:

    • Decides the value of the variable, and
    • Decides the type of the variable.

    Your first declaration has null for the value, with no way to figure out the type (it could be anything derived from System.Object, or a Nullable). That is why it is an error.

    Your second declaration pinpoints the type as Nullable because of the cast. That is why C# allows it.

    It goes without saying that double? foo = null would be much easier to read.

提交回复
热议问题