Expected result :
List<something> obj = new List<something>(); //something is i need.
string[] val = new string[] {"hi","20"}; //here I used static but input data fetch from CSV file. So we don't know when which type of data will come?.
int intval;
for(int i=0;i<val.Length;i++)
{
if(int.TryParse(val[i],out intval)
{
obj.add(intval); //here I face the error "Cannot implicitly convert int to string"
}
else
{
obj.add(val[i]);
}
}
I need to add int value and also string value into the same list. But The condition is Developer don’t know when which type of value will come. So here I used TryParse
to convert values and store into list.
How to declare a list or any other methods are there?
Note: Don't use Class to declare field and define like List<classname> val = new List<classname>();
3
Answers
Not sure why you want to do this but I think the code below is what you’re looking for. I suppose you can later check if each list value typeof is string/int but why store multi value types in one list like this?
If you just need to store all the results that you get to a single list without caring about the type then dont Parse to int type like
Just use a
List<object>
. Every type ultimately derives fromobject
: