How does the jagged array work in C# 10

What is a jagged array?

An array having different sizes and dimensions of arrays is called a jagged array.

Syntax

string[][] jaggedArray = new string[3][];

Assign arrays

Here are three different sizes of arrays assigned to the jaggedArray declared above:

jaggedArray[0] = new string[3]; // 3 element array
jaggedArray[1] = new string[2]; // 2 element array
jaggedArray[2] = new string[5]; // 5 element array

Declare and assign a jagged array

Declaration and assigning can be done together in the following way:

string[][] jaggedArray = new string[3][] {new string[3], new string[2], new string[5]};

Assign a value to a jagged array

Here is an example of assigning a value to the jagged array:

jaggedEx[2][3] = "Store this string in Array 2, Element 3";

Example

Consider the following example:

string[][] classStudents = new string[2][] {new string[2], new string[1]};
classStudents[0][0] = "Sergio"; // In classroom student
classStudents[0][1] = "Jonathan"; // In classroom student
classStudents[1][0] = "Aria"; // Online student
Console.WriteLine($"{classStudents[0][0]} and {classStudents[0][1]}: Classroom students");
// Output: Sergio and J onathan: Classroom students
Console.WriteLine($"{classStudents[1][0]}: Online student");
// Output: Aria: Online student

Explanation

  • Line 1: We declare a jagged array with 2 arrays of elements, 2 and 1, respectively.

  • Lines 3–5: We assign the values to both arrays. The first array contains the in-class student names, and the second array contains the name of the online students.

  • Line 7: We print the elements of the first array.

  • Line 10: We print the elements of the second array.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved