How can I check if an array index is out of range? Or prevent it happening.
int index = 25;
if(index >= 0 && index < array.Length)
{
//it exists
}
Source: Does Index of Array Exist
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);
}
Correct way would be
int index = 25;
if (index >= 0 && index < array.Length)
{}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With