According to Visual Studio this is not ok:
var foo = null;
But this is ok:
var foo = false ? (double?)null : null;
<
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.
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.
Implicitly typed variable declaration/assignment serves two purposes:
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.