Arrays in C# programming

Array is a collection of variables of fixed size stored in a continuous memory location. They are also known as elements. These elements are accessed by its index. The elements in an array are numbered from 0 to n-1 (n being the length of array), those numbers are called indices. For example: if we have to declare 10 elements, instead of doing it separately like, element1, element2, ....., element10, we can just do it in a single line using array, element[10].

Arrays can be divided into three types. They are

  1. Single Dimensional Array
  2. MultiDimensional Array
  3. Array of Arrays (Jagged Array)

Single Dimensional Array

In C# programming, Array can be declared using following syntax:

Syntax of Array Declaration

data_type [] array_name;

Here, data_type specifies the data type of the elements of the array. All elements of an array is of the same data type.
[ ] indicates that the variable is an array and also the size of the array.
array_name is the name of the array.

We cannot store values to an array by just declaring the array, we also have to initialize the array before using it. Initialization can be done using new keyword.

data_type [] array_name = new data_type[size_of_array];

Here, size_of_array is the total number of elements inside an array.

Initialization of values in an array can be done in many ways.
For example:

//initializing explicitly
int[] element = { 1, 2, 3};

//using index number
int[] element = new int[3];
element[0] = 1;
element[1] = 2;
element[2] = 3;

//declaration and initialization in same line
int[] element = new int[3] {1, 2, 3};

Access Elements of Single Dimensional Array

We can access the elements of an array by their index number. The first element of and array has "0" as their index and the last element has "n-1", assuming that the array has n elements. They can be accessed by their array name and the index number in square brackets after that.

We can access every element separately in an array. Elements are just like variable so we can write or read values in it. For example:

int[] element = new int[2];
element[0] = 1; //writing a value in an element
element[1] = 2;
int number;

//reading/accessing a value from an array
number = element[1]; // 2

We can also access elements of an array using foreach loop. (To learn more, visit foreach Loop in C# programming).

Example 1: C# example of use of Array

C# program to print first 5 natural numbers using array.

using System;
namespace array
{
    class Program
    {
        static void Main()
        {
            int[] numbers = { 1, 2, 3, 4, 5};
            for(int i = 0; i <= 4; i++)
            {
                Console.WriteLine(numbers[i]);
            }
        }
    }
}

Output

1
2
3
4
5

Multidimensional Array

When an array has more than one dimension, it is known as multidimensional array. Those who have two dimensions are known as two-dimensional array and three-dimensional to those have three dimensions and so on. There can be any dimensions of array, but two-dimensional and three-dimensional are mostly used. Beyond that, it gets more complicated. They can be declared as follows:

Syntax of Multidimensional Array

data_type [ , ] array_name; //two-dimensional array
data_type [ , , ] array_name; //three-dimensional array

Two-Dimensional Array


Array with two dimensions are known as two-dimensional arrays. They are also known as matrix, because the two indexes which make them look like a matrix with rows and columns. A two-dimensional array looks like this:

Declaration and Initialization of Two-Dimensional Array

It is similar to declaring one-dimensional array. It can be declared simply by using following syntax.

data_type [ , ] array_name;

Memory allocation for a two-dimensional array can be done by following following syntax:

data_type [ , ] array_name = new data_type[row_length, column_length];

We can initialize values to it individually by their indexes or straight after declaration.
For example:

//initializing individually
int[,] numbers = new int[3,2];
number[0,0] = 1;
number[0,1] = 2;
number[1,0] = 3;

//initializing after declaration
int[,] numbers = new int[3,2] { 
      {1, 2}, 
      {3, 4}, 
      {5, 6} 
      };

Access Elements of MultiDimensional Array

We can access elements of two-dimensional array simply by their index numbers, row number and column number. So, in the above example for row "0" and column "1", the element is accessed from the following statement

int num = numbers[0, 1] //2

Example 1: C# example of use of Two-Dimensional Array

C# program to read elements of a matrix and display it.

using System;
namespace matrix
{
    class Program
    {
        static void Main()
        {
            int rows, cols;
            Console.Write("Enter number of rows: ");
            r = (int)Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter number of columns: ");
            c = (int)Convert.ToInt32(Console.ReadLine());
            int[,] matrix = new int[rows, cols];
            for (int row = 0; row < rows; row++)
            {
                for (int col = 0; col < cols; col++)
                {
                    Console.Write("Enter value for matrix[{0},{1}] = ",row, col);
                    matrix[row, col] = (int)Convert.ToInt32(Console.ReadLine());
                }
            }
            Console.WriteLine("Your matrix is,");
            for (int row = 0; row < rows; row++)
            {
                for (int col = 0; col < cols; col++)
                {
                    Console.Write(matrix[row, col] + " ");
                }
                Console.WriteLine();
            }
        }
    }
}

Output

Enter number of rows: 5
Enter number of columns: 2
Enter value for matrix[0,0] = 1
Enter value for matrix[0,1] = 2
Enter value for matrix[1,0] = 3
Enter value for matrix[1,1] = 4
Enter value for matrix[2,0] = 5
Enter value for matrix[2,1] = 6
Enter value for matrix[3,0] = 7
Enter value for matrix[3,1] = 8
Enter value for matrix[4,0] = 9
Enter value for matrix[4,1] = 10
Your matrix is,
1 2
3 4
5 6
7 8
9 10

Here, the user is prompted for entering number of rows and columns in a matrix, stored in variables rows and columns respectively. Then, the program runs into a nested loop covering all rows and columns, prompting user to enter values for each cell. These values are stored in a two dimensional array matrix initialized to an array of integers with row size rows and column size columns.
Then, the program enters another nested loop. It goes through all the indices of the array and prints each value to the screen.

Array of Arrays (Jagged Array)

In C# programming, we can create array of arrays which is known as jagged array. A jagged array contains arrays as it elements. These arrays in the element can be of different sizes. 

Declaration and initialization of a jagged array

In C#, there are multiple ways to declare a jagged array, done as

//Method 1
int[][] JArray = new int[3][]; 
JArray[0] = new int[2]{1, 2}; 
JArray[1] = new int[3]{1, 2, 3};
JArray[2] = new int[4]{1, 2, 3, 4};

//Method 2
int[][] JArray = {
new int[] {1, 2},
new int[] {1, 2, 3},
new int[] {1, 2, 3, 4}
};

Access Elements of Jagged Array

The method for accessing the values from the jagged array is similar to the multidimensional array. For accessing the value from the example for row "2" and column "3", it is done as

int output = JArray[2][3]; //4

Example 1: C# example of use of Jagged Array

C# program to read elements of a jagged array and display it.

using System;
namespace matrix
{
    class Program
    {
        static void Main()
        {
            int[][] JArray = new int[3][];
            JArray[0] = new int[2] { 1, 2 };
            JArray[1] = new int[3] { 3, 4, 5 };
            JArray[2] = new int[4] { 6, 7, 8, 9 };
            Console.WriteLine("Your jagged array is:");
            for (int row = 0; row < JArray.Length; row++)
            {
                for (int col = 0; col < JArray[row].Length; col++)
                {
                    Console.Write("{0} ", JArray[row][col]);
                }
                Console.WriteLine();
            }
        }
    }
}

Output

Your jagged array is:
1 2
3 4 5
6 7 8 9