C# Jagged Array

The C# Jagged is an array whose elements are also an array, i.e., it is an array of arrays. These elements inside a C# jagged array can be of different dimensions and even can be of different sizes.

A Jagged array in C# can be declared and initialized as follows:

Int[][] JaggedAr = new int[2][];

Here size 2 represents the number of arrays, i.e., two in JaggedAr[][].

We have to initialize the arrays inside before using the Jagged.

JaggedAr[0] = new int[]{5,9,6};

JaggedAr[1] = new int[]{2,5};

Let us see an example code demonstrating on Jagged arrays.

C# Jagged Array Example

The below shown example explains you the declaration and using of the Jagged Array in C#.

using System;
 class program
     public static void Main()
         string[] NameOfEmployee = new string[2];
         NameOfEmployee[0] = "John";
         NameOfEmployee[1] = "Winson";

         string[][] JaggedAr = new string[2][];
         JaggedAr[0] = new string[] { "Bachelors", "masters", "Doctrate" };
         JaggedAr[1] = new string[] { "Bachelors", "Masters" };
         for(int i = 0;i<JaggedAr.Length;i++  )
             string[] arrayin = JaggedAr[i];
             for(int j = 0; j< arrayin.Length;j++)

C# Jagged Array 1


NameOfEmployee[] is a string array in which there are two elements.

JaggedAr[][] is a jagged having two string arrays.

JaggedAr[0] is having three elements —— Bachelors, masters, Doctorate.

JaggedAr[1] is having two elements in it —– Bachelors, Masters.

Since JaggedAr.Length is 2, When i = 0, 0<2 condition returns true. So, the control enters parent loop and prints NameOfEmployye[0] which is.


Now JaggedAr[0] is stored in arrayin[]

When j=0, j<arrayin.Length, i.e., 0<3 since JaggedAr[0] is having three elements.

0<3 returns true. So, C# prints Bachelors

Again j++, i.e., 1

Now, 1 < 3 returns true. So, it prints Masters

Again j++, i.e., 2

Next, 2 < 3 returns true, and It prints Doctorate.

Again j++, i.e., 3

Now, 3 < 3 returns false come out of child loop

Now Console.WriteLine() is executed.

Again it increments i in parent loop. This time i=1, so 1<2 returns true. Thus enters the loop and prints NameOfEmployee[1], i.e.,


arrayin = JaggedAr[1]

j=0 and j<arrayin.Length, which is 2, and it returns true. So, the control enters child loop and prints arrayin[0]


j++ = 1 and 1<2 returns true. Enters the child loop and prints arrayin[1], i.e.,


j++ = 2 and 2<2 returns false. So, it comes out of the child loop and executes.


Now increments I by 1 so i++ = 2

2<2 returns false, so comes out of the parent loop.