2.3.10 Traversing an Array With a foreach Loop

Record a Turn for Each Assigned Player

The coach wants to record one training turn for every assigned Player in a one-dimensional roster. The action needs the Player reference, not its array index, so foreach can express the traversal directly.

One roster slot is empty. The program must skip it before reading or changing a Player field.

Traverse Player References

The established Player class supplies the NumberOfTurns field. The code creates two Players and a three-element array containing their references and one null slot.

Process assigned players and skip the empty slot
Player jordan = new Player();
jordan.NumberOfTurns = 2;

Player casey = new Player();
casey.NumberOfTurns = 0;

Player[] players = { jordan, null, casey };
int playersProcessed = 0;

foreach (Player current in players)
{
    if (current != null)
    {
        current.NumberOfTurns = current.NumberOfTurns + 1;

        playersProcessed++;
    }
}

Each pass supplies the stored reference

The header foreach (Player current in players) defines current with type Player and identifies players as the array to traverse. It supplies one stored reference for each pass.

On the first pass, current reaches Jordan. On the second it contains null. On the third it reaches Casey.

These are the reference values stored in the existing array. Foreach does not create a new Player for each pass.

Let the null check guard the field update

The body's if is the first statement inside the foreach braces. When current is null, its body is skipped.

Jordan's turn count increases to 3 and Casey's to 1. playersProcessed is 2 even though foreach has made three body passes.

Inspect the Roster After Traversal
After foreach, index 0 still refers to Jordan with three turns and index 2 to Casey with one turn. Index 1 remains null. Two Players were processed in three passes.
Updated Players, unchanged roster references
  • New
  • Changed
  • Removed

The arrows show the same array references supplied by the initializer. The changed field values belong inside the Player boxes. The empty slot stays inside the array as null.

Passes and qualifying updates
Pass Current reference Turn update playersProcessed afterward
1 Jordan 2 becomes 3 1
2 null Skipped 1
3 Casey 0 becomes 1 2
Compare a Second Run