An array having different sizes and dimensions of arrays is called a jagged array.
string[][] jaggedArray = new string[3][];
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
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]};
Here is an example of assigning a value to the jagged array:
jaggedEx[2][3] = "Store this string in Array 2, Element 3";
Consider the following example:
string[][] classStudents = new string[2][] {new string[2], new string[1]};classStudents[0][0] = "Sergio"; // In classroom studentclassStudents[0][1] = "Jonathan"; // In classroom studentclassStudents[1][0] = "Aria"; // Online studentConsole.WriteLine($"{classStudents[0][0]} and {classStudents[0][1]}: Classroom students");// Output: Sergio and J onathan: Classroom studentsConsole.WriteLine($"{classStudents[1][0]}: Online student");// Output: Aria: Online student
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