2.2.10 Array Length and Valid Indexes

Find the Valid Positions in a Score Array

An array's Length tells you how many elements it contains. The last valid index is not Length: indexes begin at zero, so the last one is Length minus one.

Explore the Soccer Example

The array is initialized first. The following statements read its element count and calculate its last valid position.

Find the Valid Positions in a Score Array
int[] roundGoals = { 2, 0, 3 };
int numberOfScores = roundGoals.Length;
int lastIndex = roundGoals.Length - 1;
Check the Values
Worked soccer example
Candidate index Position exists? Reason
0 Yes First element
2 Yes One less than Length
3 No Equal to Length
-1 No Below zero
Understand the Code

Length counts elements

roundGoals.Length is 3 for this array. Reading it does not read a particular round score. It reports the number of allocated positions.

Use the range from zero to one less than Length

The valid indexes are 0, 1, and 2. Index 3 is outside the array, even though Length is 3.

Trying to access an element outside that range causes an IndexOutOfRangeException.

Separate the fixed count from changing scores

Replacing a score does not change Length. The same array still has three positions, regardless of the int stored in any one of them.

An empty array has no valid index

An array created with new int[0] is a real array whose Length is zero. There is no first element to access.

Calculating Length minus one gives -1 in this case; that result is not a valid position. Do not use it as an element index.

Distinguish an existing empty array from a missing array

new int[0] creates an array that can safely report a Length of zero. A null reference reaches no array at all, so attempting to read Length through it would fail.

For the shown populated array, the reference exists and the count is three. Use that count to identify valid positions, rather than treating the largest score or last round number as the boundary.

Try a Small Change
Predict the Result
Use the Original Diagram to Check Your Reasoning

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.

Find the Valid Positions in a Score Array.
Find the Valid Positions in a Score Array
  • New
  • Changed
  • Removed

The array box has three indexed rows. The note distinguishes the count of three elements from the largest valid index, 2. No row at index 3 exists.