Cannot assign <null> to an implicitly typed local variable
I want to select a field from the dt_branches_global data dt_branches_global so that if radioButton_QP checked, the data table will contain a string field, otherwise the data table contains an int field. This is what I do. But I get an error when initializing Var variable.
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(); The compiler is still strongly typed, so it needs to figure out the type. The compiler cannot infer what type you will assign to it null. Then you will try to assign it to two different types. An array of integers 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(); In a way, a type cannot be inferred from null - null can be any reference type.
i.e. Problem here
var AllBranch_IDs = null; is that the compiler will need to scan the following lines of code to infer the type AllBranch_IDs (which is impossible in C # anyway) and will not work due to the dynamic nature of the type - you assign it either IEnumerable<string> or IEnumerable<int> ).
You can use IEnumerable<object> and then type ints:
eg:.
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 will also compile, namely dynamic AllBranch_IDs = null , although the consumer of the result must know that the type is dynamic.