Multidimensional Array Bounds Checking


So I have a multidimensional array to contain the grid for my game. The grid wraps around, so 0 and GridWidth - 1 are essentially neighbour grid squares.

What I am trying to figure out is a better way of checking the bounds than constantly having to check:

if(x < 0)
    x = x + GridWidth;

From my understanding, the following SHOULD work:

return Grid[x % GridWidth, y % GridHeight];

and it does seem to work for anything that is above 0, but whenever the value goes negative, it is causing Array Index out of range exceptions.

Have I made a mistake in the code? Or is this just not possible in C#?


The % operator gives you a remainder. However, it doesn’t work with negative numbers, what you want is the modulus function.

You could write your own mod function that solves this:
Mod of negative number.