C# / CHAPTER 03

Create and read an array

Beginner

Store several values of one element type and inspect their positions.

By the end of this chapter

  • Declare a typed array
  • Use zero-based indexes
  • Update an existing array element

The idea

An array stores a fixed number of elements of one type. int[] scores = { 3, 5 }; creates two integer elements. The square brackets in int[] describe the type, while scores[0] reads the first stored value. Length reports the number of elements, so the final valid position is Length - 1.

An array element can change without changing the array length. scores[1] = 8; replaces the second number. An int array cannot directly store a string. Reading or writing beyond the valid indexes throws an IndexOutOfRangeException; make sure an array is nonempty before using index zero or its last index.

Begin with one array and explicit positions. The next control-flow chapter shows how foreach can visit every value. The later value/reference chapter explains what happens when two variables refer to the same array; you do not need aliasing or cloning to make and read this first array.

C# example
using System;
int[] scores = { 3, 5 };
scores[1] = 8;
Console.WriteLine(scores[0]);
Console.WriteLine(scores[scores.Length - 1]);
Console.WriteLine(scores.Length);
Result
3
8
2

Only the second element changes. The array still has two elements, at positions zero and one.

Try it yourself

Create a three-element integer array. Replace its middle number and print its first, middle, and last values.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which indexes belong to an array with three elements?