2.2.10 Initializing Arrays With Values

Overview

An array initializer creates an array and fills its positions with the listed values. It is useful when the starting data is already known. The first listed item receives index zero; commas separate items, not index numbers.

int[] seatNumbers = { 12, 14, 16 };
int chosenSeat = seatNumbers[1];
Supply Initial Values
Object diagram for initializing arrays with values: supply initial values.
Supply Initial Values
  • New
  • Changed
  • Removed

The three values give the array a length of three. Index 1 contains 14, so chosenSeat receives 14. When declaring and initializing in one statement, C# infers the array length from the listed elements. The `int[]` type still means every entry is an integer.

The initialized values belong to a specific array object. A class field declared as int[] describes the reference type but does not prescribe these particular values for every object.

Trace the Outcome

Rewrite the initializer with four values and predict the new Length and last valid index. Identify the element at index zero before using the index-one expression.