Arrays

In all of the examples we have looked at so far, each variable can hold a single value. This is very limiting. For example what if you had the need to hold a set of student names you would be forced to created a variable with a name that links to each student such as

string student01 = "Selvyn";

string student02 = "Ale";

string student03 = "Sam";

Accessing each of these variables would make the code complex because you would have to know that student01 refers to “Selvyn”. This leads to what is termed brittle code. The code breaks easily and is inflexible to change. A better approach would be to use a variable that is capable of holding multiple values of a specific type. Each entry could then be accessed using some kind of indexing system. This is the purpose of an array.

An array is a variable that holds any number of items in a contiguous manner. Items can be inserted at any point, cleared from at any point, and accessed from at any point. This gives arrays a kind of random access capability. Items can not be inserted at a point beyond the size of the array.

Example

Result

Example

Result

string[] student = { "Selvyn", "Ale", "Sam" }; for (int idx = 0; idx < student.Length; idx++) { Console.WriteLine($"{idx}: {student[idx]}"); }

The array has been created with a fixed number of items

We use a for loop to iterate across the items in the array. Each array has a Length property that can be used to determine the size of the array.

Accessing items within the array is done through the index operator []. Arrays are zero indexed. The value used in within the index operator must >= 0 and <= array size -1

string[] student = new string[3]; student[0] = "Selvyn"; student[1] = "Ale"; student[2] = "Sam"; for (int idx = 0; idx < student.Length; idx++) { Console.WriteLine($"{idx}: {student[idx]}"); }

The array is created with a fixed size but the items are all empty strings

Populating each entry in the array

 

Use the for loop to access the items in the array.

 

int[] numbers = new int[] { 3, 14, 15, 92, 6 }; foreach (int number in numbers) { Console.Write($"{number} "); }

The foreach statement: enumerates the elements of a collection and executes its body for each element of the collection.

In this example, the array is created with a fixed number of items. In the foreach satement, each item in numbers is projected one by one into the number variable. Each time a value from numbers is projected into the number the code block is executed with the current value in number. This repeats until all items within numbers have been exhausted.