Have been hearing all around ArrayList getting obsolete these days. But I do have a genuine case to use an ArrayList, like this:
ArrayList GetArrayInt()
{
ArrayList l = new ArrayList();
l.Add(2);
return l;
}
ArrayList GetArrayBool()
{
ArrayList l = new ArrayList();
l.Add(true);
return l;
}
void Process(ArrayList l)
{
foreach (var o in l)
{
if (o is int)
{
}
else
{
}
}
}
Then I call Process like this:
private void Form1_Load(object sender, EventArgs e)
{
Process(GetArrayInt());
//or
Process(GetArrayBool());
}
The bottom line is I dont need to write two Process methods separately for an ArrayList of ints and bools.
But I hear all negatives about ArrayLists. So I wanna implement it using List<T>. This is what I come up with:
List<bool> GetListBool()
{
var l = new List<bool>();
l.Add(true);
return l;
}
List<int> GetListInt()
{
var l = new List<int>();
l.Add(2);
return l;
}
void Process(List<object> l)
{
foreach (var o in l)
{
if (o is int)
{
}
else
{
}
}
}
Now how do I call it?
private void Form1_Load(object sender, EventArgs e)
{
Process(GetListInt()); //error
Process(GetListBool()); //error
Process((List<object>)GetListBool()); //error
}
The only solution here I found is to write separate Process methods for List<bool> and List<int> which is then two methods (my actual code is a lot more complex, so going by this approach I will need to write twenty such Process methods all which do the same thing).
How can I go about writing just one Process method in List<T> approach? Can List<T> replace an ArrayList even here?
Update: all the three answers work, but I liked @Phil’s answer the best. Thanks all
As Mark Gravell says, what your doing is odd, but you could use type inference and use
Process<T>(IEnumerable<T>)if you want to:The more sensible way that doesn’t require
if(item is int)etc would be to have an overload of Process for each type