Avoid IndexOutOfRangeException by looping back to start of array

I have a array [4,4] that I am looping through and printing values.

 trainingpatterns.array = new int[4, 4];
   for (int i = 0; i < 4; i++)
        {
               var element1 = x + array.coordinates[0];

                var element2 = x + array.coordinates[2];

                var element3 = x + array.coordinates[4];

                var element4 = x + array.coordinates[6];

            for (int j = 0; j < 4; j++)

            {
               var element1 = y + array.coordinates[1];

                var element2 = y + array.coordinates[3];

                var element3 = y + array.coordinates[5];

                var element4 = y + array.coordinates[7];





   Console.WriteLine(trainingpatterns.array[element2, element6]);

However my loop requires me to go over the index. So when it gets to [5,4] for example the exception will be thrown.

What I want to do is if the x value goes out of bounds, for it to loop back to the start. So for example [5,4] will print [0,4] or [6,4] will print [2,4].

I have tried using a try catch but I cannot make the function universal for all values.

Thank you.

Jon Skeet
people
quotationmark

I suspect you just want to use the % operator:

int length0 = inputArray.GetUpperBound(0);
int length1 = inputArray.GetUpperBound(1);
...

var value = inputArray[x % length0, y % length1];

Note that this will not wrap negative numbers, however - the range of a % b is (-b, +b), whereas you want [0, +b). Taking account of this is a bit more longwinded, but let me know if you need it. If your index values will always be non-negative, you don't need to worry about it.

people

See more on this question at Stackoverflow