c-sharp
  1. c-sharp-jagged-arrays

C# Jagged Arrays

In C#, a jagged array is an array of arrays, where each element of the main array can be an array of different lengths. This guide covers the syntax, usage, and considerations when working with jagged arrays in C#.

Syntax

// Declare a jagged array
dataType[][] jaggedArray = new dataType[size][];

Example

using System;

class JaggedArrayExample
{
    static void Main()
    {
        // Declare and initialize a jagged array of integers
        int[][] jaggedNumbers = new int[3][];
        
        // Initialize the subarrays with different lengths
        jaggedNumbers[0] = new int[] { 1, 2, 3 };
        jaggedNumbers[1] = new int[] { 4, 5, 6, 7 };
        jaggedNumbers[2] = new int[] { 8, 9 };

        // Access and print elements
        Console.WriteLine("Element at [1][2]: " + jaggedNumbers[1][2]);
    }
}

Output

The output will be the element at the specified index of the jagged array, in this case, jaggedNumbers[1][2].

Explanation

  • jaggedArray is a jagged array of dataType.
  • The jagged array is initialized with three subarrays of different lengths.
  • The example demonstrates accessing and printing an element from the jagged array.

Use

Jagged arrays in C# are useful when:

  • You need to represent irregular data structures where the subarrays have varying lengths.
  • The size of each subarray is not known in advance.
  • Efficient memory usage is a consideration, as jagged arrays allow for different-sized subarrays.

Important Points

  • Jagged arrays are arrays of arrays, allowing for flexibility in managing varying lengths.
  • Each subarray in a jagged array is allocated separately.
  • Accessing elements in jagged arrays requires indexing both the main array and the subarray.

Summary

C# jagged arrays provide a flexible way to work with arrays of varying lengths. Unlike rectangular arrays, jagged arrays allow each subarray to have a different size. Understanding the syntax and usage of jagged arrays will enable you to model and manipulate data structures with irregular shapes in your C# programs. Consider jagged arrays when dealing with dynamic and non-uniform datasets.

Published on: