Why we have both jagged array and multidimensional array?
Ad 3) To initialize such a monster like [][,][,]
, you can do something like:
int [,][,] multiArr1 = { { new int[,] { { 2, 2 }, { 1, 1 } },
new int[,] { { 2, 2 }, { 1, 1 } } },
{ new int[,] { { 2, 2 }, { 1, 1 } },
new int[,] { { 2, 2 }, { 1, 1 } } } };
int [,][,] multiArr2 = { { new int[,] { { 2, 2 }, { 1, 1 } },
new int[,] { { 2, 2 }, { 1, 1 } } },
{ new int[,] { { 2, 2 }, { 1, 1 } },
new int[,] { { 2, 2 }, { 1, 1 } } } };
int [][,][,] superMultiArray = { multiArr1, multiArr2 };
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.
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
A rectangular array always has the same amount of columns for every row.
MyClass[,] x = new MyClass[10,30]
Every row has 30 columns, whereas in a jagged array, this is not required. Therefore, I think you'll have to initialize every 'row' in a jagged array separately:
MyClass[][] x = new MyClass[10][];
for(int i = 0; i < 10; i++)
{
x[i] = new MyClass[30];
}
In fact, this means that not every row in the jagged array must contain the same number of elements. (In my example, it does have the same number of elements, but this is not required).
You can perfectly do this, for instance:
MyClass[][] x = new MyClass[10][];
for(int i = 0; i < 10; i++)
{
x[i] = new MyClass[(30 + i)];
}
This might be an interesting article for you.