Cannot assign null to an implicitly-typed variable

后端 未结 4 1610
傲寒
傲寒 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.
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-18 11:32

    Assigning null to a var to a value, VS can't identify what type gonna be (double,int,bool etc). Var is commonly used when you don't know what type your value gonna be.

    Your second declaration pinpoints the type as Nullable that's why you don't get an exception/error.

    0 讨论(0)
  • 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<T>). That is why it is an error.

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

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

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