|
-
Mar 28th, 2006, 09:38 AM
#1
Thread Starter
Hyperactive Member
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
-
Mar 28th, 2006, 09:46 AM
#2
Re: Using foreach with an ArrayList
Here is a very interesting article on using (actually, NOT using) foreach.
-
Mar 28th, 2006, 10:47 AM
#3
New Member
Re: Using foreach with an ArrayList
 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!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|