C-SHARP - 3.5 Painting (Démo)

We are now back on Visual Studio to put arrays into practice. To create an array we declare its type (here string because we want to store first names), add square brackets, give the array a name (for example prenoms) and use the new keyword to allocate memory. We repeat the element type and put the size between brackets. With new string[3] we have an instance of an array able to hold three strings. There are then two ways to assign values to it.

string[] prenoms = new string[3] { "Jibril", "Jason", "Jean-Mai" };

string[] prenomsBis = new string[3];
prenomsBis[0] = "Jibril";
prenomsBis[1] = "Jason";
prenomsBis[2] = "Jean-Mai";

Console.WriteLine(prenoms[0]);

The first way provides every value right after the size, inside braces. Each value sits at an index: 0 for the first, 1 for the second, and so on. The second way assigns each cell individually using prenoms[0] = "Jibril";. If you try to write outside the allocated size (for example index 3 on an array of three), the program will not compile and warns you about the wrong length.

Exercise

  • Create a string array containing Tom, Idriss, Thibault and Rachid.
  • Use the shortest syntax (initializer between braces).
  • Display the values in the order: Rachid, Idriss, Thibault, Tom on a single line.

To display a value, call Console.WriteLine and pass prenoms[index]. The correction uses one Console.WriteLine with concatenation: ordre[3] + " " + ordre[1] + " " + ordre[2] + " " + ordre[0]. Writing a line per name works too but does not scale to a thousand names; that is the role of loops, which we will see in a later video. See you in the next lesson.