How do you wrap back to the first weapon?

One operator. And one trap going backwards.

How do you wrap back to the first weapon?

The problem

An if at both ends.

void Next(){    _i++;    if ( _i >= _weapons.Length ) _i = 0;} void Previous(){    _i--;    if ( _i < 0 ) _i = _weapons.Length - 1;}

Two directions, two edge cases, and an easy off by one waiting in each.

The fix

Let the remainder wrap it.

% gives the remainder after dividing. It counts up to one less than the length, then starts again at 0.

( i + 1 )%length→0, 1, 2, 0, 1

The fix in code

Next, in one line.

void Next(){    _i = ( _i + 1 ) % _weapons.Length;}

Three weapons: 0, 1, 2, then back to 0.

Watch out

Going back gives -1.

void Previous(){    _i = ( _i - 1 ) % _weapons.Length;    // at 0: -1 % 3 is -1, not 2}

In C#, % keeps the sign. -1 % 3 is -1, and _weapons[-1] throws.

The fix

Add the length first.

void Previous(){    _i = ( _i - 1 + _weapons.Length ) % _weapons.Length;}

Adding the length keeps it positive, so -1 becomes 2.

The rule

Wrap with %. Add the length going back.

Forward
( i + 1 ) % n
Backward
( i - 1 + n ) % n
Without + n
-1, and a crash