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)
{}
Author by
RandomGuy
Updated on July 22, 2022Comments
-
RandomGuy almost 2 years
How can I check if an array index is out of range? Or prevent it happening.
-
Mr.Bigglesworth about 7 yearsTypo there array.Length not array.Legth (being picky)
-
Brandon Kramer about 7 yearsLength is misspelled.
-
dcg about 7 yearsFixed right now. Thanks.
-
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 about 7 yearsFor 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. over 5 yearsit will fail when someone passes any value less than
0
. so need an additional check asindex >= 0
which combines the if statement to becomeif(index >= 0 && index < array.Length){}
-
matt about 4 yearsThis should be built in as a member function of the array class..
-
moto_geek almost 4 yearstypo.. s/b Length (uppercase)