2.2.11 Array Length and Valid Indexes

Overview

A one-dimensional array has positions from zero through `Length - 1`. Length counts elements; it is not the index of the final element. Accessing Length as an index tries to read beyond the array and fails at runtime.

int[] seats = { 12, 14, 16 };
int count = seats.Length;
int lastSeat = seats[seats.Length - 1];
Stop Before Length
Object diagram for array length and valid indexes: stop before length.
Stop Before Length
  • New
  • Changed
  • Removed

Count is 3 and lastSeat is 16. Valid indexes are 0, 1, and 2. The expression `seats[3]` is invalid. For an empty array, Length is zero, so there is no last element to read; check for a nonzero length first.

Loop conditions commonly use i < seats.Length. Equality with Length belongs to the exit check, not to an element access.

Trace the Outcome

For arrays of length 1, 3, and 0, state the valid index range. Decide whether `Length - 1` can safely be accessed in each case.