Why we have both jagged array and multidimensional array?
Solution 1:
A jagged array is an array-of-arrays, so an
int[][]
is an array ofint[]
, each of which can be of different lengths and occupy their own block in memory. A multidimensional array (int[,]
) is a single block of memory (essentially a matrix).-
You can't create a
MyClass[10][20]
because each sub-array has to be initialized separately, as they are separate objects:MyClass[][] abc = new MyClass[10][]; for (int i=0; i<abc.Length; i++) { abc[i] = new MyClass[20]; }
A
MyClass[10,20]
is ok, because it is initializing a single object as a matrix with 10 rows and 20 columns. -
A
MyClass[][,][,]
can be initialized like so (not compile tested though):MyClass[][,][,] abc = new MyClass[10][,][,]; for (int i=0; i<abc.Length; i++) { abc[i] = new MyClass[20,30][,]; for (int j=0; j<abc[i].GetLength(0); j++) { for (int k=0; k<abc[i].GetLength(1); k++) { abc[i][j,k] = new MyClass[40,50]; } } }
Bear in mind, that the CLR is heavily optimized for single-dimension array access, so using a jagged array will likely be faster than a multidimensional array of the same size.
Solution 2:
A jagged array is an array of arrays. Each array is not guaranteed to be of the same size. You could have
int[][] jaggedArray = new int[5][];
jaggedArray[0] = new[] {1, 2, 3}; // 3 item array
jaggedArray[1] = new int[10]; // 10 item array
// etc.
It's a set of related arrays.
A multidimensional array, on the other hand, is more of a cohesive grouping, like a box, table, cube, etc., where there are no irregular lengths. That is to say
int i = array[1,10];
int j = array[2,10]; // 10 will be available at 2 if available at 1