loading...

how to fix Index was outside the bounds of the array error?

waelelsayegh1 profile image Wael El-Sayegh ・1 min read

i am trying to access an array elements and make some Logic gates operations over it, so basically i am trying to get the neighbors of each element, but i am getting the error, Index was outside the bounds of the array error.. thats one of my conditional if statements, and i know i am trying to access an element which is not exist either less than 0 element position or bigger than or = array.length

                if (states[i] == 0 && states[i + 1] == 0)
                {
                    states[i] = 0;
                }

any idea how to fix it?

Discussion

markdown guide
 

If you are intentionally accessing something outside the array, put the code in a try/catch block:

try {
    // put code here
}
catch(IndexOutOfRangeException ex)
{
    // handle error here
}
 

Never attempt to catch an IndexOutOfRangeException when using arrays. This exception can be avoided simply by making sure your index is within the range - which in arrays means larger than -1 and smaller than array.Length.

For more information, read Eric Lippert's blog post entitled Vexing Exceptions

 

Nope, it is not intentionally the purpose here is only to check the element neighbors only

 

I don't get this code. You're setting the array cell to 0 if it is 0 - why?

 

to check the neighbors of the element in the array

 

this line states[i] = 0; doesn't make sense inside this condition, because you already know that the value in states[i] is 0.

And as for the exception - if you know i is smaller than the array's length, it means that i+1 must be equal to the array's length to throw that exception - so, guessing that this i is a for loop variable, you need the loop to stop one step before - so for(var i = 0; i < arr.Length - 1; i++) {/* do stuff here */}