Kamran
Kamran

Reputation: 4100

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();

Upvotes: 9

Views: 39093

Answers (2)

StuartLC
StuartLC

Reputation: 107387

As it stands, the type cannot be inferred from null - null could be any reference type.

i.e. The problem here

var AllBranch_IDs = null;

is that the compiler would need to scan to the following lines of code to deduce the type of AllBranch_IDs (which isn't possible in C# anyway), and wouldn't work due to the dynamic nature of the type - you assign it either IEnumerable<string> or IEnumerable<int>).

You could use IEnumerable<object> and then box the ints:

e.g.:

     IEnumerable<object> AllBranch_IDs = null;

     if (new Random().Next(10) > 5)
     {
        AllBranch_IDs = new [] {1,2,3,4}.Cast<object>().ToArray();
     }
     else
     {
        AllBranch_IDs = new [] {"hello", "world"}.ToArray();
     }

Declaring it as dynamic would also compile, viz dynamic AllBranch_IDs = null, although the consumer of the result would need to be aware that the type is dynamic.

Upvotes: 6

Oskar Kjellin
Oskar Kjellin

Reputation: 21900

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();

Upvotes: 11

Related Questions