Working with Jagged Arrays in C#: Flexible Array Structures

Learn how to create and use jagged arrays in C# to handle arrays with varying inner array lengths. This tutorial provides a comprehensive guide with examples demonstrating how to declare, initialize, and manipulate jagged arrays for flexible data representation.



Working with Jagged Arrays in C#

Introduction

A jagged array in C# is an array of arrays. Unlike a multidimensional array where all inner arrays have the same size, a jagged array's inner arrays can have different lengths. This provides flexibility when you need arrays with varying numbers of elements in each row.

Declaring a Jagged Array

You declare a jagged array by specifying the number of outer arrays and then using `[]` for each inner array:

Declaring a Jagged Array

int[][] myJaggedArray = new int[2][]; // Declares a jagged array with 2 outer elements

This creates a jagged array with two elements. Each of these elements will be an integer array itself.

Initializing a Jagged Array

Each inner array must be created separately and initialized. You can specify the size of each inner array:

Initializing a Jagged Array

myJaggedArray[0] = new int[4]; //Inner array 0 will have 4 elements
myJaggedArray[1] = new int[6]; //Inner array 1 will have 6 elements

You can also initialize and populate the arrays simultaneously:

Initializing and Populating

myJaggedArray[0] = new int[] { 11, 21, 56, 78 };
myJaggedArray[1] = new int[] { 42, 61, 37, 41, 59, 63 };

Example: Creating and Traversing a Jagged Array

Jagged Array Example

using System;

public class JaggedArrayTest {
    public static void Main(string[] args) {
        int[][] arr = new int[2][];
        arr[0] = new int[] { 11, 21, 56, 78 };
        arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };

        for (int i = 0; i < arr.Length; i++) {
            for (int j = 0; j < arr[i].Length; j++) {
                Console.Write(arr[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}
Example Output

11 21 56 78 
42 61 37 41 59 63
        

Initializing During Declaration

You can also initialize a jagged array directly during declaration:

Initialization During Declaration

int[][] arr = new int[3][] {
    new int[] { 11, 21, 56, 78 },
    new int[] { 2, 5, 6, 7, 98, 5 },
    new int[] { 2, 5 }
};

Conclusion

Jagged arrays are a flexible way to represent arrays of arrays with varying inner array lengths. They're useful when you don't know the exact dimensions of your data beforehand or when you need a more adaptable array structure.