Results 1 to 3 of 3

Thread: Using foreach with an ArrayList

  1. #1

    Thread Starter
    Hyperactive Member drattansingh's Avatar
    Join Date
    Sep 2005
    Posts
    395

    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

  2. #2
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: Using foreach with an ArrayList

    Here is a very interesting article on using (actually, NOT using) foreach.

  3. #3
    New Member
    Join Date
    Feb 2003
    Posts
    14

    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!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width