C# Jagged Arrays

Jagged Arrays are also known as “array of arrays” that is because the elements are arrays themselves. Their dimensions and sizes may be different.

Declaration of jagged array in C#.

Jagged array can be declared and created in a following way.

//declaration
int [][] marks;

//creating to allocate memory
int[][] marks = new int[5][];

Initialization of Jagged array in C#

As told above, a jagged array can be a different size. As the elements inside the arrays are the arrays themselves so they may vary in dimension. Let us see an example.

You can initialize array in different ways, one of which is:

//Initializing in single line
int[][] marks = new int[2][]{
               new int[]{88,90,60},
               new int[]{45,80,55,92}
             };

As you can see, we initialize it in a single line with a new operator for each array element with a different dimension. One has 3 integers while the other have 4 integers.

You can also separately initialize them with index number such as:

marks[0] = new int[3] { 88,90,60 };         
marks[1] = new int[4] { 45,80,55,92 };  

Let us understand with an example:


C# program illustrates using a jagged array

Nested for loop is used to traverse through jagged array.

using System;

namespace Arrays
{
   class JaggedArrays
   {
      static void Main(string[] args)
      {
         //jagged arrays initialization
         int[][] arr = new int[][]
         {
            new int[]
               { 0, 1 },
               new int[]
               { 2, 3 },
               new int[]
               { 4, 5 },
               new int[]
               { 6, 7 }
         };

         //displaying
         for (int i = 0; i < 4; i++)
            for (int j = 0; j < 2; j++)
               Console.WriteLine("arr[{0}][{1}] = {2}", i, j, arr[i][j]);

      }
   }
}

Output:

arr[0][0] = 0
arr[0][1] = 1
arr[1][0] = 2
arr[1][1] = 3
arr[2][0] = 4
arr[2][1] = 5
arr[3][0] = 6
arr[3][1] = 7