As discussed in the previous chapter, Arrays in C# will support multi-dimensional arrays. In c#, a multidimensional array is an array that contains more than one dimension to represent the elements in a tabular format like rows and columns.
In c#, multidimensional arrays can support either two or three-dimensional series. To create multi-dimensional arrays, we need to use a comma (,) separator inside the square brackets.
In c#, Multidimensional Arrays can be declared by specifying the data type of elements followed by the square brackets [] with comma (,) separator. The following are examples of creating two or three-dimensional arrays in the c# programming language.
If you observe the above examples, we created a two-dimensional array (arr) with 4 rows, 2 columns, and another array (arr1) with three dimensions 4, 2, 3.
In c#, we can initialize arrays upon declaration. Following are the different ways of declaring and initializing multidimensional arrays in the c# programming language.
If you observe the above examples, we declared and initialized a two-dimensional array with 3 rows and 2 columns and a three-dimensional array with 2, 2, 3 dimensions.
In the second and fourth statements, while declarations, we initialized arrays with values without specifying any dimensions. Here, the dimensions of an array can be determined by the number of elements, so the dimension initializers are not required if we assign elements during the initialization.
The following diagram will illustrate more details about how multidimensional arrays will be divided into rows and columns in the c# programming language.
If you observe the above diagram, we defined a two-dimensional array with 3 rows, 2 columns and inserted the elements in an array based on the defined number of elements.
In c#, we can access the values of multidimensional arrays by using the row index and column index values.
Following is the example of accessing elements from multidimensional arrays in c# programming language based on our requirements.
If you observe the above example, we are accessing elements of two or three-dimensional arrays by passing index values.
Following is the example of using multidimensional arrays in c# programming language to represent the elements in an array with multiple dimensions.
If you observe the above example, we created two and three-dimensional arrays and got those array values using for loop in c#.
When we execute the above c# program, we will get the result below.
If you observe the above result, we are able to get the two or three-dimensional arrays by using respective index values based on our requirements.
In c#, multidimensional arrays are slower than single-dimensional arrays while accessing elements from arrays. Instead of multidimensional arrays, we can use jagged arrays in c# to improve the application's performance.
This is how we can use multidimensional arrays in our c# applications based on our requirements.