2

Why does a [,] style array Length method vs a [][] jagged style array Length method differ in that in the jagged array the length method returns the size of the closest rank where as in the [,] style array the Length method returns the whole number of elements not only of the closest rank (hence the need to use the GetLength() method.)

Johnson
  • 401
  • 5
  • 14
  • @PatrickKostjens I have read that but i don't understand the difference in the Length method specifically. i Mean why would the length method in jagged arrays differ in the result that the length method in the "normal" arrays. Is there any reason? – Johnson Mar 30 '16 at 14:19
  • Because `Length` returns the number of elements in the array. In a multi-dimensional array, this is naturally the total number of elements, since you have 1 array containing n elements. A jagged array is actually and array of arrays, so `Length` returns the number of arrays – Kevin Gosse Mar 30 '16 at 14:23
  • Because a `something[x]` contains x elements. It shouldn't make a difference whether `something` is `int`, `string` or `somethingElse[]`. A `something[x, y]` on the other hand, is one object that contains x*y elements. – Dennis_E Mar 30 '16 at 14:24

1 Answers1

2

Jagged arrays ([][]) arrays where the element type is an array too [], so basically is just a one-dimension array.

Multidimensional arrays ([,]) are arrays that have more than one dimension, but all elements are in the same array.

Length property from MSDN:

Gets the total number of elements in all the dimensions of the Array.

According to this Length in jagged array this property returns the number of arrays it contains.

In multidimensional arrays this property returns all elements in it, that is the multiplication of all dimension sizes.

GetLength(int) from MSDN:

Gets an integer that represents the number of elements in the specified dimension of the Array.

Using this method for jagged arrays, the only available dimension is 0, that returns the same value as Length property.

In multidimensional arrays you can pass the zero-based index of the desired dimension. For example in [,,] available dimensions are 0, 1 and 2.

Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53