C# Multidimensional Arrays

In the previous section, you have learned about the one-dimensional array. In C# we can create multidimensional arrays as well. These arrays are something like matrics. The multidimensional array stores the values in a row and column format.

Let's understand about the multidimensional array with an image. Following image shows a two-dimensional array.

Array Declaration

Following is the syntax to declare a multidimensional array.

dataType[,] variableName;           Two dimensional array
dataType[,,] variableName;          Three dimensional array

dataType[,] variableName = new dataType[size,size];              Three dimensional array
dataType[,,] variableName = new dataType[size,size,size];        Three dimensional array

Multidimensional arrays can be declared by placing two brackets [] after the type name followed by the variable name. The brackets[] contains the number of commas(') according to the array dimension.

Following are the different types of array declarations.

int[,] array; //Two dimensional array
string[,,] Names; //Three dimensional array
string[,,,] Address; //Four dimensional array

Array Initialization

Multi-dimensional arrays can also be initialized while their declaration. Following are the different ways to initialize a multidimensional array.

By using the new keyword.

int[,] Numbers = new int[4, 2]; //Two dimensional array
string[,,] Names = new string[4, 2, 2];//Three dimensional array

By doing late initialization with the new keyword. Remember if the size is specified in the brackets then you must add the same number of values while doing late initialization.

// Two-dimensional array.
int[,] Numbers2D = new int[4,2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; //Two-dimensional integer array
string[,] Names2D = new string[4,2]{{"a","b"},{"c","d"},{"e","f"},{"g","h"}};//Two-dimensional string array

This was the overview and explanation of C# Multidimensional array. Let's learn about the C# Jaggaed array in the next section.