How can I check if an array index is out of range? Or prevent it happening.
3 Answers
int index = 25;
if(index >= 0 && index < array.Length)
{
//it exists
}
Source: Does Index of Array Exist
-
3For 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.– SerliteMar 1, 2017 at 16:28
-
3it 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){}
Jul 29, 2018 at 20:24 -
2Related: Answers entirely copied though properly attributed - e.g., "...simply tacking a "Reference" link at...a wall of unquoted text...does not count as proper attribution". Oct 2, 2022 at 14:52
-
2
-
1I prefer to write
if(0 <= index && index < array.Length)
, for simmetry, math-like style, and (in my mind) clarity of "index is inside the semiopen interval [0, Length)".– Pablo HOct 19, 2022 at 16:43
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);
}
-
2
Correct way would be
int index = 25;
if (index >= 0 && index < array.Length)
{}
-
-
It seems like a rehashing of the copied answer (a copy of a copy). The magic number, 25, comes from the corresponding question. Oct 2, 2022 at 14:53
-
@PeterMortensen I don't get what you mean - if what you trying to say is that I copied the answer that's incorrect– dcgOct 3, 2022 at 15:07
Array.Length
to avoid using an index that is out of range. But judging from your comment you have an issue where you are using an incorrect index in the first place, where are you getting this index from and what's causing it to be out of range? You don't seem keen on posting any code though and the question has been answered. Good luck.