C# Multidimensional Array
In C#, a multidimensional array is an array that contains one or more arrays. A multidimensional array can be considered as an array of arrays.
Declaring a Multidimensional Array
A multidimensional array can be declared in the following way:
1// Two-dimensional array 2int[,] myArray = new int[3, 4]; 3 4// Three-dimensional array 5int[,,] myOtherArray = new int[2, 3, 4];
The above code declares a two-dimensional array with three rows and four columns and a three-dimensional array with two levels, three rows, and four columns.
Accessing Elements of a Multidimensional Array
To access an element of a multidimensional array, we need to specify the indices of the element that we want to access. For example, to access the element in the second row and third column of a two-dimensional array, we can write:
1int[,] myArray = new int[3, 4]; 2int element = myArray[1, 2];
Initializing a Multidimensional Array
We can initialize a multidimensional array using the following syntax:
1int[,] myArray = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
This initializes a two-dimensional array with three rows and two columns.
We can also initialize a multidimensional array using nested for loops. For example, to initialize a two-dimensional array with the numbers from 1 to 12, we can write:
1int[,] myArray = new int[3, 4]; 2int counter = 1; 3 4for (int i = 0; i < 3; i++) 5{ 6 for (int j = 0; j < 4; j++) 7 { 8 myArray[i, j] = counter; 9 counter++; 10 } 11}