locked
array list elements RRS feed

  • Question

  • How can I check to see is a item in array item exsist before trying to access it. In the example below the for example the arraylist BestAvailableToBackPrices[] may have 0 elements or upto 3 elements. If element is not present a “System.ArgumentOutOfRangeException” is thrown. Ive being trying to check for “null” but this does not work. Any help please  

     

       

            x1 = Convert.ToString(gameFeed.Selection[k].BestAvailableToBackPrices[1].Value));

            x2 = Convert.ToString(gameFeed.Selection[k].BestAvailableToBackPrices[1].AmountUnmatched));

            x3 = Convert.ToString(gameFeed.Selection[k].BestAvailableToLayPrices[1].Value));

            x4 = Convert.ToString(gameFeed.Selection[k].BestAvailableToLayPrices[1].AmountUnmatched));

    Wednesday, October 18, 2006 12:36 PM

Answers

  • the reason you will get an argumentOutOfRangeException is because you are trying to access an element which exceeds the length of the array, that the length/position specified does not exist in the array, you have gone over the max length of that array length.

    One way would be to either iterate through each item in the array and see if there is an item, in question, that exists. If not, then do whatever you want.

    Example:

     

    bool itemFound = false;

    for (int counter = 0; counter < theArray.Length; counter++)

    {

       if (theArray[counter].Equals(value) && itemFound = false)

       { 

          //item exists

          itemFound = true;

       }

    }

     

    if (itemFound) { ....//do whatever...}

    Wednesday, October 18, 2006 1:17 PM