C# two dimensional array with double bracket and with single bracket<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog

# C# two dimensional array with double bracket and with single bracket

Posted on: October 16, 2013

With Microsoft .Net and C# it's possible to have multiple dimension array with two different ways. One use double bracket and one with single bracket with a comma.

`1int [][] myDoubleArray = new int[100][];`
`1int [,] mySingleArrayActingAsTwoDimensional = new int[100,100];`

The first example, is in fact an array of array. You can have multiple dimension for your second dimension. It's called a jagged array.

`1int [][] myDoubleArray = new int[100][]; 2myDoubleArray[0] = new int[5]; 3myDoubleArray[1] = new int[10]; 4myDoubleArray[2] = new int[50]; 5myDoubleArray[...] = new int[...];`

This lead to the possibility to have a variable that is not uniform in its size, it can but it doesn't mean it is a perfect rectangle. The second way to make a multiple dimensional array is by using the comma. This force to have the size defined for both dimension and to be the same for each rows. It also not possible to get a row like array of array because it's based on index.

`1int [,] mySingleArrayActingAsTwoDimensional = new int[100,100]; 2mySingleArrayActingAsTwoDimensional[50] = ... // CRASH!!! mySingleArrayActingAsTwoDimensional[50,0] = 1;`

For the jagged array, to loop through all items, we must check for each array. This is require to get its size because it can change.

`1for (int i = 0; i < myDoubleArray.Length; i++) { 2  for (int j = 0; j < myDoubleArray[i].Length; j++) { 3    myDoubleArray[i][j] = i * j; 4  } 5}`

For a rectangle array, it's not required and we can just check the first item lenght.

`1for (int i = 0; i < mySingleArrayActingAsTwoDimensional.GetLength(0); i++) { 2  for (int j = 0; j < mySingleArrayActingAsTwoDimensional.GetLength(1); j++) { 3    mySingleArrayActingAsTwoDimensional[i, j] = i * j; 4  } 5}`

Finally, you can create jagged array with a short nomenclature.

`1var jaggedArrayTwoDimension= {new int[5] 2 ,new int[10]3 , new int[]{1,2,3,4,5,6,7,8,9,10}};`

The last example create an array of 2 dimensions. 3 rows, the first one has 5 integers, the second has 10 integer and the last rows and 10 integers. The first two rows are integer not defined and the last row has integer defined from 1 to 10.