In C#, a multidimensional array is an array that contains more than one dimension, such as a two-dimensional array or a three-dimensional array.
A two-dimensional array is an array of arrays, where each inner array represents a row of the array. A three-dimensional array is an array of arrays of arrays, where each innermost array represents a plane of the array.
Here is an example of how you can declare and initialize a two-dimensional array in C#:
1 2 3 4 5 6 7 8 | int[,] array = new int[3, 3] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; |
This array has 3 rows and 3 columns, and it contains the values 1, 2, 3, 4, 5, 6, 7, 8, and 9.
You can access the elements of a multidimensional array using the indexing syntax. For example, to access the element at row 1 and column 2 of the array, you can use the following code:
1 2 3 | int element = array[1, 2]; |
This will assign the value 6 to the element
variable.
You can also use a loop to iterate through the elements of a multidimensional array. Here is an example of how you can use a nested loop to print all the elements of a two-dimensional array:
1 2 3 4 5 6 7 8 9 10 | for (int i = 0; i < array.GetLength(0); i++) { for (int j = 0; j < array.GetLength(1); j++) { Console.Write(array[i, j] + " "); } Console.WriteLine(); } |
This will output the following:
1 2 3 4 5 | 1 2 3 4 5 6 7 8 9 |
Here are three examples of multidimensional arrays in C#:
Two-dimensional array:
1 2 3 4 5 6 7 8 | int[,] array = new int[3, 3] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; |
This array has 3 rows and 3 columns, and it contains the values 1, 2, 3, 4, 5, 6, 7, 8, and 9.
Three-dimensional array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | int[,,] array = new int[2, 3, 2] { { { 1, 2 }, { 3, 4 }, { 5, 6 } }, { { 7, 8 }, { 9, 10 }, { 11, 12 } } }; |
This array has 2 planes, 3 rows, and 2 columns, and it contains the values 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, and 12.
Jagged array:
1 2 3 4 5 6 7 8 | int[][] array = new int[3][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 }, new int[] { 8, 9 } }; |
This array is an array of arrays, where each inner array represents a row. The rows have different lengths, which makes this a jagged array. This array contains the values 1, 2, 3, 4, 5, 6, 7, 8, and 9.