What is the difference between jagged array and Multidimensional array. Is there a benefit of one on another?
And why would the Visual Studio not allow me to do a
MyClass[][] abc = new MyClass[10][20];
(We used to do that in C++, but in C# it underlines [20] with red wriggly line.. Says invalid rank specifier)
but is happy with
MyClass[,] abc = new MyClass[10,20];
Finally how can I initialize this in a single line (like we do in simple array with {new xxx...}{new xxx....}
)
MyClass[][,][,] itemscollection;
There are several benefits of using jagged arrays. One of the most crucial advantages is that it makes things easy where there is a need to store data in a multidimensional way using the same variable name. Furthermore, it helps in memory management which makes the program to be executed very smoothly and fast as well.
Jagged arrays are a special type of arrays that can be used to store rows of data of varying lengths to improve performance when working with multi-dimensional arrays. An array may be defined as a sequential collection of elements of the same data type.
A jagged array is an array-of-arrays, so an int[][]
is an array of int[]
, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With