Cannot assign null to an implicitly-typed variable

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.


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.

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.

Tags:

C#