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.
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][];`.
using System;
class Program {
static void Main() {
int[,] grid = { {1, 2}, {3, 4} };
Console.WriteLine(grid[0, 1]);
Console.WriteLine(grid[1, 0]);
}
}2
3grid[0,1] accesses row 0, column 1, and grid[1,0] accesses row 1, column 0.
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);
}
}3
1Each 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.
