C-SHARP - 3.4 Painting

This video introduces the array in C#. An array is a data structure that lets us store several variables of the same type inside one container. If we need three first names, declaring three independent string variables is wasteful: as developers we want optimised programs, so we group them in a single array. The declaration follows three steps: the type of the elements, square brackets to mark the array nature, then a name. Finally we allocate memory with new followed again by the type and the size between brackets.

int[] nombres = new int[3];

nombres[0] = 10;
nombres[1] = 20;
nombres[2] = 30;

int[] autresNombres = { 1, 2, 3 };

The line above creates an integer array called nombres and reserves room for three values. Behind the scenes the System.Array class is used to build the array, which is why the new keyword is required to allocate memory. Once the array exists we access its elements through their index, which is written between square brackets. In C# and in most programming languages, indexes start at 0: an array of three elements has indexes 0, 1 and 2, not 1, 2, 3.

Two ways to fill an array

  • Assign each cell one by one using its index: nombres[0] = 10;.
  • Provide every value at once inside braces when you know them in advance.
  • Always respect the declared size, otherwise you will get an IndexOutOfRange error.

We can also set the values when we declare the array: provide them between braces in the right order and the compiler infers the size. We will explore arrays in more detail later in the course; for now head to Visual Studio and try the syntax to make these notions stick.