CSharp - C# Arrays

Introduction

Array is a fixed number of variables for a particular type.

An array is denoted with square brackets after the element type.

All arrays inherit from the System.Array class.

For example, the following code declares an array of 5 characters:

char[] vowels = new char[5];    

Square brackets index the array, accessing a particular element by position:

vowels[0] = 'a';
vowels[1] = 'e';
vowels[2] = 'i';
vowels[3] = 'o';
vowels[4] = 'u';
Console.WriteLine (vowels[1]);      // e

Array indexes start at 0.

We can use a for loop statement to iterate through each element in the array.

The for loop in the following code iterates from 0 to 4:

for (int i = 0; i < vowels.Length; i++)
       Console.Write (vowels[i]);            // aeiou

Length property of an array returns the number of elements in the array.

Once an array is created, its length cannot be changed.

Quiz