Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

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

like image 632
RandomGuy Avatar asked Mar 01 '17 16:03

RandomGuy


3 Answers

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

Source: Does Index of Array Exist

like image 124
GKG4 Avatar answered Nov 20 '22 08:11

GKG4


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);
}
like image 10
Warcaith Avatar answered Nov 20 '22 07:11

Warcaith


Correct way would be

int index = 25;
if (index >= 0 && index < array.Length)
{}
like image 6
dcg Avatar answered Nov 20 '22 07:11

dcg