How can I check if an array index is out of range?

56,429

Solution 1

int index = 25;
if(index >= 0 && index < array.Length)
{
    //it exists
}

Source: Does Index of Array Exist

Solution 2

Another way of checking if an array is out of bounds is to make a function. This will check if the index is "in bounds". If the index is below zero or over the array length you will get the result false.

private bool inBounds (int index, int[] array) 
{
    return (index >= 0) && (index < array.Length);
}

Solution 3

Correct way would be

int index = 25;
if (index >= 0 && index < array.Length)
{}
Share:
56,429
RandomGuy
Author by

RandomGuy

Updated on July 22, 2022

Comments

  • RandomGuy
    RandomGuy almost 2 years

    How can I check if an array index is out of range? Or prevent it happening.

  • Mr.Bigglesworth
    Mr.Bigglesworth about 7 years
    Typo there array.Length not array.Legth (being picky)
  • Brandon Kramer
    Brandon Kramer about 7 years
    Length is misspelled.
  • dcg
    dcg about 7 years
    Fixed right now. Thanks.
  • RandomGuy
    RandomGuy about 7 years
    <3 Thanks, thats it, but i have to check on multiple arrays at the sametime, and if it is right according to the DB. But i figured it out. Thanks anyway. Take Care!
  • Serlite
    Serlite about 7 years
    For future reference, if you find another question that you believe has the exact answer, don't duplicate that answer into your own answer. Instead, click the "flag" option under a question, choose "Flag to close > Duplicate question", and choose the appropriate question.
  • Jamshaid K.
    Jamshaid K. over 5 years
    it will fail when someone passes any value less than 0. so need an additional check as index >= 0 which combines the if statement to become if(index >= 0 && index < array.Length){}
  • matt
    matt about 4 years
    This should be built in as a member function of the array class..
  • moto_geek
    moto_geek almost 4 years
    typo.. s/b Length (uppercase)