Patrick Desjardins Blog
Patrick Desjardins picture from a conference

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

Posted on: 2013-10-16

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.

 int [][] myDoubleArray = new int[100][]; 
 int [,] 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.

int [][] myDoubleArray = new int[100][]; 
myDoubleArray[0] = new int[5]; 
myDoubleArray[1] = new int[10]; 
myDoubleArray[2] = new int[50]; 
myDoubleArray[...] = 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.

int [,] mySingleArrayActingAsTwoDimensional = new int[100,100]; 
mySingleArrayActingAsTwoDimensional[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.

for (int i = 0; i < myDoubleArray.Length; i++) { 
  for (int j = 0; j < myDoubleArray[i].Length; j++) { 
    myDoubleArray[i][j] = i * j; 
  } 
} 

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

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

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

 var jaggedArrayTwoDimension= {new int[5] 
 ,new int[10]
 , 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.