×

c# · level 1 · unit 6 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Every item in an array has an , starting at 0.

Each item has an index: its position number. C# starts counting at 0, so the first item is planets[0] and the second is planets[1]. Square brackets after the name pick one out.

So the last item is always at Length - 1. To change an item, put a new value in its slot: planets[1] = "Mars";. An array's size is fixed, so you cannot add slots.

Ask for a slot that is not there and C# stops with an , an error that happens while the program runs. This one is called IndexOutOfRangeException.

using System;

string[] planets = { "Mercury", "Venus", "Earth" };
Console.WriteLine(planets[0]);
Console.WriteLine(planets[planets.Length - 1]);
planets[1] = "Mars";
Console.WriteLine(string.Join(", ", planets));

Think of the index as how many steps from the start, so the first item is 0 steps away.