C# ยท Chapter 22 of 46

C# Multidimensional Arrays

A multidimensional array stores data in more than one dimension, like a grid of rows and columns. C# supports rectangular arrays (fixed-size grids) and jagged arrays (arrays of arrays with varying lengths).

Multidimensional arrays are useful for representing tables, matrices, or grids, such as a tic-tac-toe board or a spreadsheet of numbers.

Syntax
type[,] name = new type[rows, cols];
type[][] jagged = new type[length][];

Rectangular arrays

A 2D rectangular array is declared with `int[,] grid = new int[2,3];`, where every row has the same number of columns. Elements are accessed with two indexes, like grid[0,1].

Jagged arrays

A jagged array is an array of arrays, where each inner array can have a different length, declared as `int[][] jagged = new int[3][];`.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    int[,] grid = { {1, 2}, {3, 4} };
    Console.WriteLine(grid[0, 1]);
    Console.WriteLine(grid[1, 0]);
  }
}
Output
2
3

grid[0,1] accesses row 0, column 1, and grid[1,0] accesses row 1, column 0.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    int[][] jagged = new int[2][];
    jagged[0] = new int[] { 1, 2, 3 };
    jagged[1] = new int[] { 4 };
    Console.WriteLine(jagged[0].Length);
    Console.WriteLine(jagged[1].Length);
  }
}
Output
3
1

Each inner array of a jagged array can have a different length.

Key points

  • Rectangular arrays use [,] and have equal-length rows.
  • Jagged arrays use [][] and rows can have different lengths.
  • Elements in a 2D array are accessed with [row, col].
  • Multidimensional arrays are useful for grids and tables of data.
๐Ÿ’ก Note: Jagged arrays are often more memory-efficient than rectangular arrays when row lengths vary a lot.

๐Ÿ“ Quick Quiz

1. How do you declare a 2D rectangular array?

2. What is a jagged array?

3. How do you access row 1, column 2 of a 2D array named grid?