3

What is the difference between the two syntaxes?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
Dollarslice
  • 9,917
  • 22
  • 59
  • 87

3 Answers3

8

The first one is a multi dimensional array while the second is a jagged array. You can take a look at this question to get a description of the diffrerence between the two, but here is an important snippit:

A multidimensional array creates a nice linear memory layout while a jagged array implies several extra levels of indirection.

Looking up the value jagged[3][6] in a jagged array var jagged = new int[10][5] works like this: Look up the element at index 3 (which is an array) and look up the element at index 6 in that array (which is a value). For each dimension in this case, there's an additional look up (this is an expensive memory access pattern).

A multidimensional array is laid out linearly in memory, the actual value is found by multiplying together the indexes. However, given the array var mult = new int[10,30] the Length property of that multidimensional array returns the total number of elements i.e. 10 * 30 = 300.

The Rank property of a jagged array is always 1, but a multidimensional array can have any rank. The GetLength method of any array can be used to get the length of each dimension. For the multidimensional array in this example mult.GetLength(1) returns 30.

Indexing the multidimensional array is faster e.g. given the multidimensional array in this example mult[1,7] = 30 * 1 + 7 = 37, get the element at that index 37. This is a better memory access pattern because only one memory location is involved, which is the base address of the array.

A multidimensional array therefore allocates a continuous memory block, while a jagged array does not have to be square like. e.g. jagged1.Length does not have to equal jagged[2].Length which would be true for any multidimensional array.

Update:

One major difference between the multi and jagged array is that a multi must always be "square", meaning that any two indexes will have the same number of elements in their child arrays. A jagged array does not have this requirement. Take a look at the code below:

var jagged = new int[3][]; //not defining the size of the child array...
var multi = new int[3,8]; //defining a 3x8 "square"
var multiBad = new int[3,]; //Syntax error!
var jaggedSquare= new int[3][8]; //another 3x8 "square"
Community
  • 1
  • 1
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
2

The former is a two dimensional array. The latter is an array whose elements are also arrays.

Chris Shain
  • 50,833
  • 6
  • 93
  • 125
2

The first is for a multidimentional array

the second is for array of arrays

Gir
  • 839
  • 5
  • 11