Roadmap › C# Language — Basics to Advanced › Module: Arrays and Collections
Lessons in this course (38)

9. Arrays: single, multidimensional and jagged

Basic★ Must knowLesson 9 of 38

An array is a fixed-size, zero-indexed block of elements of one type. Arrays are reference types (derived from System.Array), even when the elements are value types.

csharp
int[] marks = new int[5];                 // five zeros
int[] primes = { 2, 3, 5, 7 };            // initializer
string[] cities = ["Pune", "Taipei"];     // collection expression (C# 12)

marks[0] = 90;
Console.WriteLine(primes.Length);         // 4
Console.WriteLine(primes[^1]);            // 7 — index from end
int[] middle = primes[1..3];              // { 3, 5 } — range creates a copy
// primes[10] = 1;                        // IndexOutOfRangeException

// Multidimensional (rectangular) array: one block, every row same length
int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
Console.WriteLine(grid[1, 2]);            // 6
Console.WriteLine(grid.GetLength(0));     // 2 rows
Console.WriteLine(grid.GetLength(1));     // 3 columns
for (int r = 0; r < grid.GetLength(0); r++)
    for (int c = 0; c < grid.GetLength(1); c++)
        Console.Write(grid[r, c] + " ");

// Jagged array: an array of arrays, rows can have different lengths
int[][] jagged = new int[3][];
jagged[0] = [1];
jagged[1] = [1, 2];
jagged[2] = [1, 2, 3];
Console.WriteLine(jagged[2][1]);          // 2
foreach (int[] row in jagged) Console.WriteLine(string.Join(",", row));

Useful Array methods: Array.Sort(arr), Array.Reverse(arr), Array.IndexOf(arr, x), Array.Find(arr, predicate), Array.Resize(ref arr, newSize) (creates a new array and copies), Array.Copy, Array.Fill, arr.Clone() (shallow copy).

Multidimensional int[,]Jagged int[][]
ShapeRectangular — all rows equalRows can differ
MemoryOne contiguous objectOuter array + one array per row
Accessa[r, c]a[r][c]
SpeedSlightly slower indexing in the CLRUsually faster, more flexible