Why use Arrays?

You already know that you can store one bit of data in a variable. But what if you want to store more data? For example you may want to store a list of player names or a set of test scores. You could use lots of variables, but that would take time and start to get confusing.

Benefits of Arrays:

  • Arrays allow you to store multiple items together using one identifier... the array name e.g. PlayerScores
  • This reduces the need for several different variables to store the data.

Creating arrays with data

Method 1: Create an Array and then add data.

Creating an array is a little more complicate that creating a variable. Not only do you have to give the data type, you need to use square brackets to indicate an array. You also need to allocate memory using the new keyword. The example will store five petnames as strings.

string[] petNames = new string[5];

In the pet names example, you can add the names by referring to the array index. This is entered in square brackets after the array name. Array positions start at zero:

petNames[0] = "Coco";
petNames[1] = "Fentan";
petNames[2] = "Fluff";
petNames[3] = "Pooch";
petNames[4] = "Bounder";

This example will store 10 test scores.

int[] testScores = new int[10];

Method 2: Create the array with the data

If you know the names already you can create the array and fill it immediately:

string[] petNames = new string[] { "Coco", "Button", "Cleo", "Fritz", "Cupcake" };

Display data from the array

Method 1: Display each item one by one

You could display each name like this:

MessageBox.Show(petNames[0]);
MessageBox.Show(petNames[1]);
MessageBox.Show(petNames[2]);
MessageBox.Show(petNames[3]);
MessageBox.Show(petNames[4]);

Method 2: Use iteration (a loop) to display the data

The following for loop will create and initialise the variable x at zero. Each loop will increment x by one. It will continue while x is less than 4.

for (int x = 0; x < 5; x++)
{
    MessageBox.Show(petNames[x]);
}

Learn more..

DOTNETPERLS W3SCHOOLS