Why we have both jagged array and multidimensional array?

C#.NetArraysVisual Studio-2010

C# Problem Overview


  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;
    

C# Solutions


Solution 1 - C#

  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.

Solution 2 - C#

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

Solution 3 - C#

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.

Solution 4 - C#

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 };

Solution 5 - C#

If you're looking for a multi-dimensional array that has set bounds, always use the [,] style syntax. This will make sure that each portion is equally sized.

When you use [][] what is really going is that you're creating an array of arrays. This then means that each array can be sized differently. For example:

int[][] jaggedArray = new int[5][]
for(int index = 0; index < jaggedArray.Length ; ++index)
{
    jaggedArray[index] = new int[index + 1];
}

Solution 6 - C#

The inline declaration would look something like this:

int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };

Solution 7 - C#

For #1, see this SO question

For jagged or multidimensional inline arrays, see this programming guide:

// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };

// Same array with dimensions specified at declaration.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };

You don't have to specify the dimensions (array3D), but if you know they're never going to change, it's helpful to know what dimensions you're using (array3Da).

Solution 8 - C#

For a multi-dimensional array think of a box or rectangle. Each row is the same length and each column is the same length.

In a jagged array, the rows and columns may not be the same size. For example, the columns or rows may be different sizes. This would lead to a shape that may not be a straight line down the sides like a rectangle. Instead the sides may be jagged.

Now I used 2 dimensions/2 arrays for this example, but this applies to more.

Solution 9 - C#

You would need to understand the internal working of the array the multi-dimensional array act as a single dimension array except that the double indexing is converted into a single one.

Your Jagged array in c# is an array of objects which are in turns arrays.

Solution 10 - C#

I think that 2d jagged arrays memory allocation in C# is like 2d arrays in C++ and C. Because 2d jagged arrays have pointer which points to array of pointers that each of this pointers points to an array of elements (for example integer elements); like this code in C++,

int** 2DArr {new int* [number1]};
for (int i = 0; i < number1; i++)
{
   2DArr[i] = new int[number2];
}

the memory allocation of code bellow is the same as 2d jagged arrays in C#. But i am doubtful about , could you please explain more if i think in wrong way.

Solution 11 - C#

This post is old but here are my thoughts on that.

Jagged arrays are multidimensional arrays. Multidimensional arrays come in two varieties: rectangular and jagged. Rectangular arrays represent an n-dimensional block of memory, and jagged arrays are arrays of arrays.

Rectangular arrays

Rectangular arrays are declared using commas to separate each dimension. The following statement declares a rectangular two-dimensional array, where the dimensions are 3 × 3:

int[,] matrix = new int [3, 3]; 

Jagged arrays

Jagged arrays are declared using successive square brackets to represent each dimension. Here is an example of declaring a jagged two-dimensional array, where the outermost dimension is 3:

int[][] matrix = new int[3][];

Solution 12 - C#

 public class ArrayExamples    
{
            //Multi-Dimensional Array are of 2 types
            //1. Jagged Array: Array of Arrays
            //2. rectangular Array: Array having more than one dimension
            public void JaggedArray()
            {
                //Declaring an array with 3 element. Each element containing single dimension array.
                //Benefit: Each single dimension array defined can be of different length.
                int[][] jaggedArray = new int[3][];
    
                jaggedArray[0] = new int[] { 1, 2, 3, 4, 5 };//single dimension array lengh:5
                jaggedArray[1] = new int[] { 6,7,8};//single dimension array lengh:3
                jaggedArray[2] = new int[] { 9, 10 };//single dimension array lengh:2
    
                foreach (var array in jaggedArray)
                    foreach (var element in array)
                    {
                        Console.WriteLine(element);
                    }
            }
    
    
            public void RectangularArray()
            { 
                //Declaring a 2 dimensional array with  5 rows and 2 columns.
                //Benefits: When we want to declare an array with multiple dimension
                //and we know the length as length should be predefined.
                //
    
                int[,] array2Dimensional = new int[5,2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 }, { 9, 10 } };
    
    
                //This loop will go through all the elements
                //This will display all the elements i.e. 1,2,3,4,5,6,7,8,9,10
                foreach (var element in array2Dimensional)
                {
                   //Console.WriteLine(element);
                }
    
                //Accessing specific element in the 2 dimensional array.
                //i.e. will display 1 which is the first element of first row and first column.
                Console.WriteLine(array2Dimensional[0, 0]);
            }
        }

Solution 13 - C#

A Multi-dimensional array is a rectangular array in C#. It can only have a fixed number of elements in each dimension. The following code example shows us how we can declare a multi-dimensional array in C#.

int[,] multiArray = new[3,3]

A jagged array is an array of arrays in C#. It can constitute arrays of different sizes in it. The following code example shows us how we can declare a jagged array in C#.

int[][] jaggedArray = new int[3][];
            jaggedArray[0] = new int [1];
            jaggedArray[1] = new int[2];
            jaggedArray[2] = new int[3];

In the above code, we created the jagged array jaggedArray of size 3, which means that the jaggedArray is an array of 3 arrays. These 3 arrays are at the index 0, 1, and 2 of the jaggedArray. It is clear from the example that all these arrays are of different sizes.

The jagged arrays should be preferred over the conventional multi-dimensional arrays because of their flexibility in C#. For example, if we have to store a person’s hobbies, the preferred approach would be to use a jagged array because not everyone has the same number of hobbies. The same thing goes for interests and many other things.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShekhar_ProView Question on Stackoverflow
Solution 1 - C#thecoopView Answer on Stackoverflow
Solution 2 - C#Anthony PegramView Answer on Stackoverflow
Solution 3 - C#Frederik GheyselsView Answer on Stackoverflow
Solution 4 - C#nanView Answer on Stackoverflow
Solution 5 - C#Joshua RodgersView Answer on Stackoverflow
Solution 6 - C#Josiah RuddellView Answer on Stackoverflow
Solution 7 - C#rownageView Answer on Stackoverflow
Solution 8 - C#RoblemView Answer on Stackoverflow
Solution 9 - C#dvhhView Answer on Stackoverflow
Solution 10 - C#A.R.S.D.View Answer on Stackoverflow
Solution 11 - C#Imir HoxhaView Answer on Stackoverflow
Solution 12 - C#maxspanView Answer on Stackoverflow
Solution 13 - C#Muhammad JunaidView Answer on Stackoverflow