5

I am currently trying to learn C#, and I ran across following question:

What is the difference between [,] and [][] in a type in C#?

CodenameLambda
  • 1,486
  • 11
  • 23

1 Answers1

12

[,] form creates rectangular two dimensional array. When you specify the dimensions you will get a two dimensional matrix of those sizes. All its elements are initialized to the default value of the element type.

int[,] array = new int[4, 2];

Memory-wise, the array is stored as a single block in memory (of size width*height). Accessing an element is a little slower and the runtime does more expensive operations - see http://blog.mischel.com/2013/05/08/are-jagged-arrays-faster-than-rectangular-arrays/

[][] is called jagged array and it is basically an array of arrays. When you create it, you first only specify the size of the first dimension:

int[][] jaggedArray = new int[3][];

Now you have to create a new array for each of the rows manually (they are initially null)

jaggedArray[0] = new int[10];
jaggedArray[1] = new int[6];

The advantage of this is that each row can have a different length.

In memory, each of the rows is stored in a different location, but accessing a specific element is ultimately faster, because it just requires the runtime to find the pointer to the row array in the base array and then find the requested element as in a normal array.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91