Use an index inside square brackets to read one array element. The array name identifies the sequence, and the index identifies the position within it.
The following statements read scores without changing the array.
int[] roundGoals = { 2, 0, 3 };
int firstScore = roundGoals[0];
int index = 2;
int chosenScore = roundGoals[index];Read one position
roundGoals[0] reads the int at the first position, which is 2. The assignment copies that value into firstScore. The other array positions are not involved.
An index can come from a variable
The local index contains 2. Therefore roundGoals[index] reads the same position as roundGoals[2] and produces 3.
The name index is not special C# syntax. Its stored integer determines which position is accessed.
Reading does not move or remove the value
After both reads, the array is still 2, 0, 3. The assignments copied int values into separate locals; they did not remove any element or alter Length.
Check the index before the access
For this three-element array, the chosen index must be at least zero and below 3. Changing it to 3 would cause an exception at the access statement, not at the earlier assignment int index = 3;.
Follow the reference and then the selected position
The expression roundGoals[index] first needs an existing array and a valid index. Once those are available, it produces the int stored in that position.
The assignment to chosenScore copies that int. If the array element is corrected later, chosenScore will not automatically recalculate; it keeps the value read when its own assignment executed.
| Expression | Index used | Value read |
|---|---|---|
roundGoals[0] |
0 | 2 |
roundGoals[index] when index is 2 |
2 | 3 |
roundGoals[1] |
1 | 0 |
The diagram below shows the original example. Compare it with your prediction for the requested change; its pictured values have not been replaced by the practice inputs.
The chosen index selects the row marked [2]. Its value 3 is copied into chosenScore. The array box still shows all three original values after the read.