Reputation: 73183
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
Upvotes: 1
Views: 501
Reputation: 42991
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:
void Main()
{
Process(GetInts());
Process(GetBools());
}
IEnumerable<int> GetInts()
{
return new List<int>{1,2,3};
}
IEnumerable<bool> GetBools()
{
return new List<bool>{true, false, true};
}
void Process<T>(IEnumerable<T> items)
{
foreach (var item in items)
{
if(item is int)
{
Debug.WriteLine("int: " + item.ToString());
}
if(item is bool)
{
Debug.WriteLine("bool: " + item.ToString());
}
}
}
The more sensible way that doesn't require if(item is int)
etc would be to have an overload of Process for each type
void Process(IEnumerable<int> items) { foreach(...) };
void Process(IEnumerable<bool> items) { foreach(...) };
Upvotes: 1
Reputation: 2884
You can use LINQ to convert a type-safe list to List<object>
:
List<object> objList = GetListBool().Cast<object>().ToList();
Upvotes: 1
Reputation: 1062865
It is an odd example, and isn't very OOP, but: you could indeed use List<int>
, List<bool>
, etc - and change the return type / parameter type to the non-generic IList
or IEnumerable
. Odd example though.
Upvotes: 3