A valid row does not make every column valid. For a rectangular array, each coordinate must fit the size of its own dimension.
The coach requests row 1, column 3 from a record containing two teams and three rounds. The row exists, but the requested column does not.
| Coordinate | Requested value | Valid range | Result |
|---|---|---|---|
| Team row | 1 | 0 through 1 | Valid |
| Round column | 3 | 0 through 2 | Invalid |
The whole pair is invalid because one coordinate fails. Checking only the row or comparing the column with the total Length would not protect this access.
int[,] teamGoals = { { 2, 0, 3 }, { 1, 4, 2 } };
int row = 1;
int column = 3;
int selectedScore = -1;
bool validPair = row >= 0 && row < teamGoals.GetLength(0) && column >= 0 && column < teamGoals.GetLength(1);
if (validPair)
{
selectedScore = teamGoals[row, column];
}Separate candidate values from an actual access
Defining row as 1 and column as 3 does not itself read an array element. The access occurs only in teamGoals[row, column] inside the if.
This makes it possible to check the candidate pair before using it.
Require all four boundary checks
The row and column must each be nonnegative and below their own dimension count. The AND operators require every check to succeed.
For the shown values, the final check fails because 3 < 3 is false. validPair is false, so the element read is skipped.
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 score-reading action is only on the true route. The shown column takes the false route and leaves the initial marker unchanged. The diagram's dimension counts match the initializer.