In C#, a multidimensional array is an array that contains elements organized in multiple dimensions. The most common type of multidimensional array is a two-dimensional array, but C# also supports arrays with more than two dimensions.
Here’s an example of declaring and initializing a two-dimensional array in C#:
int[,] twoDimensionalArray = new int[3, 4];
In this example, twoDimensionalArray
is a two-dimensional array with 3 rows and 4 columns. The new int[3, 4]
part initializes the array with the specified dimensions and allocates memory to store the elements.
You can access and assign values to individual elements using indices:
twoDimensionalArray[0, 0] = 1; // Set value at row 0, column 0 int value = twoDimensionalArray[1, 2]; // Get value at row 1, column 2
C# also allows you to initialize the array with values:
int[,] twoDimensionalArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
This initializes the array with the specified values. In this case, twoDimensionalArray
is a 3×3 array.
C# also supports multidimensional arrays with more than two dimensions. Here’s an example of declaring and initializing a three-dimensional array:
int[,,] threeDimensionalArray = new int[2, 3, 4];
In this case, threeDimensionalArray
is a three-dimensional array with 2 levels, 3 rows, and 4 columns.
You can access and assign values in a similar way as the two-dimensional array, but you’ll need to specify the indices for each dimension:
threeDimensionalArray[0, 1, 2] = 42; // Set value at level 0, row 1, column 2 int value = threeDimensionalArray[1, 2, 3]; // Get value at level 1, row 2, column 3
That’s an overview of how to work with multidimensional arrays in C#. Remember to adjust the dimensions and indices according to your specific needs.
C# Multidimensional Array Example: Declaration and initialization at same time
Certainly! Here’s an example of declaring and initializing a multidimensional array in C#:
int[,] twoDimensionalArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
In this example, twoDimensionalArray
is a 3×3 array that is declared and initialized at the same time using the curly brace syntax. The inner curly braces represent each row, and the values within each row represent the elements of the array.
You can access and manipulate the elements of the multidimensional array using indices, just like in the previous example:
int value = twoDimensionalArray[1, 2]; // Get value at row 1, column 2 twoDimensionalArray[0, 1] = 10; // Set value at row 0, column 1
You can also use a similar syntax for initializing multidimensional arrays with more than two dimensions. Here’s an example with a three-dimensional array:
int[,,] threeDimensionalArray = { { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }, { { 10, 11, 12 }, { 13, 14, 15 }, { 16, 17, 18 } } };
In this example, threeDimensionalArray
is a 2x3x3 array that is declared and initialized with two levels, each containing a 3×3 array.
Feel free to adjust the dimensions and values to suit your specific needs.