Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign <null> to an implicitly-typed local variable

I want to to select a field from Data table dt_branches_global in such a way that, if radioButton_QP is Checked then the Data table will contain a string field otherwise the Data Table contain an int field. This is what I am doing. But I am getting error while initializing the variable Var.

var AllBranch_IDs = null;

if (radioButton_QP.Checked == true)   
AllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<string>("BusinessSectorID")).ToArray();
else

AllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<int>("BusinessSectorID")).ToArray();
like image 552
Kamran Avatar asked Jun 27 '14 10:06

Kamran


People also ask

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

In C#, the compiler does not allow you to assign a null value to a variable.

What is implicitly typed variables 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.


1 Answers

The compiler is still strongly typed so it needs to figure out the type. It is impossible for the compiler to infer the type of you assign it to null. Then you later on try to assign it to two different types. An array of ints and an array of strings.

Try something like:

string[] AllBranch_IDs = null;

if (radioButton_QP.Checked == true)   
AllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<string>("BusinessSectorID")).ToArray();
else

AllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<int>("BusinessSectorID").ToString()).ToArray();
like image 196
Oskar Kjellin Avatar answered Sep 21 '22 13:09

Oskar Kjellin