According to Visual Studio this is not ok:
var foo = null;
But this is ok:
var foo = false ? (double?)null : null;
Why? Is the (double?)null
affecting also the null
in the else branch?
The following restrictions apply to implicitly-typed variable declarations: var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
Implicitly typed variables are those variables which are declared without specifying the . NET type explicitly. In implicitly typed variable, the type of the variable is automatically deduced at compile time by the compiler from the value used to initialize the variable.
In C#, you can assign the null value to any reference variable. The null value simply means that the variable does not refer to an object in memory. You can use it like this: Circle c = new Circle(42); Circle copy = null; // Initialized ... if (copy == null) { copy = c; // copy and c refer to the same object ... }
In C#, the compiler does not allow you to assign a null value to a variable. So, C# 2.0 provides a special feature to assign a null value to a variable that is known as the Nullable type. The Nullable type allows you to assign a null value to a variable.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With