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.
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.
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.
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.
| Pass | Current reference | Turn update | playersProcessed afterward |
|---|---|---|---|
| 1 | Jordan | 2 becomes 3 | 1 |
| 2 | null | Skipped | 1 |
| 3 | Casey | 0 becomes 1 | 2 |