Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign null to an implicitly-typed variable

Tags:

c#

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?

like image 662
user2061057 Avatar asked Jan 25 '18 12:01

user2061057


People also ask

Can a implicitly typed variable be set to null?

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.

How do you initialize an implicitly typed variable in C#?

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.

How do you assign a variable to null in C#?

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 ... }

Can we assign null in Var and dynamic in C#?

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.


2 Answers

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.

like image 118
Sergey Kalinichenko Avatar answered Sep 20 '22 01:09

Sergey Kalinichenko


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.
like image 30
Manprit Singh Sahota Avatar answered Sep 19 '22 01:09

Manprit Singh Sahota