Iterating through an array and staying within bounds Sorry if this question has been asked before, but I am having trouble searching for the answer I am looking for. This question is in regards to efficiency and overall C# standards.

I have an integer that I manipulate by 1, either by -- or ++ depending on a user's input. I then use this integer as an index to grab an object out of an array. I would like to know what the best way to make sure this variable will always stay within the confines of the array, such that if the user reached the end of the array, it would loop back to the beginning and continue from there. This is an example of the logic I am using for that:

switch(directionMoved)
{
    case MoveDirection.Left:
        currentPageIndex--;
        break;

    case MoveDirection.Right:
        currentPageIndex++;
        break;
}

if (currentPageIndex &lt; 0)
{
    var distanceFromZero = currentPageIndex;
    currentPageIndex = objectArray.Length + distanceFromZero;
}

if (currentPageIndex &gt;= objectArray.Length)
{
    var distanceFromEnd = currentPageIndex - objectArray.Length;
    currentPageIndex = distanceFromEnd;
}

...

(use 'currentPageIndex' to grab from array)


Is there a cleaner way to do this same logic? I hope my questions was clear... =]

Thanks!
You can use % remainder operator to be sure the value will be within bounds:

if (directionMoved == MoveDirection.Left) currentPageIndex--;
if (directionMoved == MoveDirection.Right) currentPageIndex++;

currentPageIndex += objectArray.Length;
currentPageIndex %= objectArray.Length;


This wiil allow you iterate in a circular way between 0 and objectArray.Length - 1.