Why we have both jagged array and multidimensional array?

Shekhar_Pro picture Shekhar_Pro · Jan 10, 2011 · Viewed 48.1k times · Source
  1. What is the difference between jagged array and Multidimensional array. Is there a benefit of one on another?

  2. 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];
    
  3. Finally how can I initialize this in a single line (like we do in simple array with {new xxx...}{new xxx....})

    MyClass[][,][,] itemscollection;
    

Answer

thecoop picture thecoop · Jan 10, 2011
  1. 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).

  2. 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.

  3. 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.