Using foreach with an ArrayList
hi. I'm trying to use the foreach statement with the ArrayList. Here is a sample of my code:
ArrayList AList = new ArrayList();
AList.Add("hi");
AList.Add("ko");
AList.Add("dr");
AList.Add("cvdf");
foreach(int x in AList)
{
// some code
}
I'm getting an invalid cast exception. Anyone knows why? - Jennifer
Re: Using foreach with an ArrayList
Here is a very interesting article on using (actually, NOT using) foreach.
Re: Using foreach with an ArrayList
Quote:
Originally Posted by JenniferBabe
hi. I'm trying to use the foreach statement with the ArrayList. Here is a sample of my code:
ArrayList AList = new ArrayList();
AList.Add("hi");
AList.Add("ko");
AList.Add("dr");
AList.Add("cvdf");
foreach(int x in AList)
{
// some code
}
I'm getting an invalid cast exception. Anyone knows why? - Jennifer
The primary reason for your 'invalid cast' error is that you are inserting string objects eg. AList.Add("dr");, but then using 'int x' as the type of objects you want to search.
Change it to:
foreach(String x in AList)
{
//some code
}
This should work.
Hope this helps!
:wave: