C# - Arrays


An array represents a fixed number of elements of a particular type. The elements in an array are always stored in a contiguous block of memory, providing highly efficient access.

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

char[] vowels = new char[5]; // Declare an array of 5 characters

Square brackets also 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

This prints ā€œeā€ because array indexes start at 0. We can use a for loop statement to iterate through each element in the array. The for loop in this example cycles the integer i from 0 to 4:

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

The Length property of an array returns the number of elements in the array. Once an array has been created, its length cannot be changed. The System.Collection namespace and subnamespaces provide higher-level data structures, such as dynamically sized arrays and dictionaries.

An array initialization expression specifies each element of an array. For example:

    char[] vowels = new char[] {'a','e','i','o','u'};

or simply:

    char[] vowels = {'a','e','i','o','u'};

All arrays inherit from the System. Array class providing common services for all arrays.

Multidimensional Arrays

Multidimensional arrays come in two varieties: rectangular and jagged. Rectangular arrays represent an n-dimensional block of memory, and jagged arrays are arrays of arrays

Rectangular arrays

Rectangular arrays are declared using commas to separate each dimension. The following declares a rectangular two-dimensional array, where the dimensions are 3 by 3:

    int [,] matrix = new int [3, 3];

The GetLength method of an array returns the length for a given dimension (starting at 0):

        for (int i = 0; i < matrix.GetLength(0); i++)
            for (int j = 0; j < matrix.GetLength(1); j++)
                matrix [i, j] = i * 3 + j;

A rectangular array can be initialized as follows (each element in this example is initialized to be identical to the previous example):

      int[,] matrix = new int[,]

Jagged arrays

A jagged array provides more flexibility in sizing the array. With a jagged array every row can have a different size.

A jagged array is declared by placing one pair of opening and closing brackets after another. To initialize the jagged array, only the size that defines the number of rows in the first pair of brackets is set. The second brackets that define the number of elements inside the row are kept empty because every row has a different number of elements. Next, the element number of the rows can be set for every row:

    int[][] jagged = new int[3][];
    jagged[0] = new int[2] { 1, 2 };
    jagged[1] = new int[6] { 3, 4, 5, 6, 7, 8 };
    jagged[2] = new int[3] { 9, 10, 11 };

You can iterate through all the elements of a jagged array with nested for loops. In the outer for loop every row is iterated, and the inner for loop iterates through every element inside a row:

        for (int row = 0; row < jagged.Length; row++)
            for (int element = 0; element < jagged[row].Length; element++)
                Console.WriteLine("row: {0}, element: {1}, value: {2}", row, element,

Array Class

Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime.

Most common properties of Array class

Properties Name Description Example
Length Returns the length of array. Returns integer value. int i = arr1.Length;
Rank Returns total number of items in all the dimension. Returns integer value. int i = arr1.Rank;
IsFixedSize Check whether array is fixed size or not. Returns Boolean value bool i = arr.IsFixedSize;
IsReadOnly Check whether array is ReadOnly or not. Returns Boolean value bool k = arr1.IsReadOnly;

Most common functions of Array class

Methods Name Description Example
Sort Sort an array Array.Sort(arr);
Clear Clear an array by removing all the items Array.Clear(arr, 0, 3);
GetLength Returns the number of elements arr.GetLength(0);
GetValue Returns the value of specified items arr.GetValue(2);
IndexOf Returns the index position of value Array.IndexOf(arr,45);
Copy Copy array elements to another elements Array.Copy(arr1,arr1,3);

ForEach Loop

The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects.

So, if you have an array, you could use the foreach statement to iterate through the array, like so:

    int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
    foreach (int i in fibarray)

You could also use it to iterate through a List collection, like so:

List list = new List();
foreach (string item in list)