skip to content

In C#, when should a level editor's tile map be an `int[,]` rather than an `int[][]`, and what does each one give up?

level: middleimportance: should knowfreq 50%

answer

  1. one object or many
  2. rectangle versus ragged rows
  3. Rank, GetLength and Length
  4. rows start out null
  5. CS0022 when taking a row

basics

~20 s

Use int[,] for a fixed rectangular map: one object, equal-length rows, grid[y, x] checked on both indexes. Use int[][] when rows differ in length or are passed around alone: each row is a separate int[] that starts null.

solid answer

~40 s

`int[,]` is a **multidimensional** array: one object whose `Rank` is 2, whose `Length` is rows times columns and whose sizes come from `GetLength(0)` and `GetLength(1)`; its elements are stored row by row and every row has the same length. That fits a rectangular tile map, and `Clone()` copies every tile. It gives up row access: `grid[1]` is CS0022, `grid[^1, 0]` is CS0029, a collection expression cannot build it (CS9174) and it does not convert to `Span<int>`. `int[][]` is a **jagged** array, an `int[]` of row references: rows may differ in length, each row is a normal `int[]` that works with `^1`, spans and collection expressions, and rows can be swapped. It gives up rectangularity: rows start `null`, each is a separate allocation, and `Clone()` copies only the references.

code

csharp · 17 lines
csharp
int[,] grid = new int[3, 4];           // one object holding 12 ints, row-major
grid[2, 3] = 7;
Console.WriteLine($"Rank={grid.Rank} Length={grid.Length} rows={grid.GetLength(0)} cols={grid.GetLength(1)}");

int[][] rows = new int[3][];           // three null references, no rows yet
try { rows[0][0] = 1; }
catch (NullReferenceException) { Console.WriteLine("rows[0] was never allocated"); }

rows = [[1, 1, 1, 1], [2, 2], []];     // rows of different lengths
int[] lastRow = rows[^1];              // a row is an ordinary int[]
Console.WriteLine($"Rank={rows.Rank} Length={rows.Length} last row length={lastRow.Length}");

var gridCopy = (int[,])grid.Clone();   // copies all 12 ints
gridCopy[2, 3] = 0;
var rowsCopy = (int[][])rows.Clone();  // copies 3 references, shares the rows
rowsCopy[0][0] = 42;
Console.WriteLine($"grid[2,3]={grid[2, 3]} rows[0][0]={rows[0][0]}");

go deeper

for a junior

Know both declarations, that int[,] uses grid[y, x] and int[][] uses rows[y][x], and that jagged rows must be allocated before use.

for a middle

Explain one object versus an array of row references, what Rank, Length and GetLength return for each, and which compile errors appear when an int[,] is treated as rows.

for a senior

Choose the shape from how the code touches the data: whole-map edits and copies favour int[,], row-wise processing with spans or ragged data favour int[][]. Catch the shallow Clone bug in undo snapshots.

for a principal

This is a local data-structure choice, not a team policy; the useful lead input is keeping one representation per subsystem so conversions between grid shapes do not spread through the codebase.

## Two array shapes in C# C# has two ways to hold a grid of values, and they are different types, not two spellings of one: - A **multidimensional array** (also called a rectangular array) such as `int[,]` is **one object** with a fixed size in each dimension. `new int[3, 4]` creates 12 elements, and every one of the 3 rows has exactly 4 columns. - A **jagged array** such as `int[][]` is an **array of arrays**: an outer `int[]`-of-references whose elements are separate `int[]` objects. `new int[3][]` creates the outer array with three `null` references and no rows at all. The docs describe the multidimensional enumeration order as rightmost index first, and the runtime's `Array.GetFlattenedIndex` computes the element position as row times width plus column, after checking each index against its own dimension. ## How they compare | | `int[,] grid` | `int[][] rows` | |---|---|---| | Objects | one | one outer array plus one per row | | `Rank` / `Length` | 2 / rows × columns | 1 / number of rows | | Size of a dimension | `GetLength(0)`, `GetLength(1)` | `rows.Length`, `rows[i].Length` | | Access | `grid[y, x]`, both indexes checked | `rows[y][x]`, two separate array accesses | | Rows of different lengths | impossible | allowed, including empty rows | | Taking a row | impossible | `int[] row = rows[y]` | | `Clone()` | copies every element | copies the row references only | | Default state | every element zero | every row `null` | ## What `int[,]` gives up The SDK's compiler rejects every attempt to treat a multidimensional array as a list of rows: 1. `int[] row = grid[1];` fails with **CS0022** ("Wrong number of indices inside []; expected 2"). 2. `grid[^1, 0]` fails with **CS0029**: index-from-end support covers single-dimensional arrays and countable types with a single `int` indexer, so the `Index` cannot become an `int` here. 3. `int[,] g = [[1, 2], [3, 4]];` fails with **CS9174**: the type is not constructible from a collection expression. Use the older initializer `{ { 1, 2 }, { 3, 4 } }`. 4. `Span<int> s = grid;` fails with **CS0029**; spans wrap single-dimensional arrays. 5. An `int[,]` does not implement `IEnumerable<int>`, so `grid.Select(...)` does not compile (CS0411) and you write `grid.Cast<int>()` to query it with LINQ. In exchange you get a structure that **cannot become ragged**, one allocation, and a `Clone()` that copies the whole map. ## What `int[][]` gives up - **Rows start as `null`.** Writing `rows[0][0] = 1` after `new int[3][]` throws `NullReferenceException`; you must allocate every row. - **Rectangularity is a convention, not a rule.** Nothing stops one row from being shorter, so code that assumes a width needs its own checks. - **Many allocations.** A 1,000-row map is 1,001 objects, and the rows can sit anywhere on the heap. - **Shallow copies.** `Clone()` copies the outer array; both copies share the same row arrays, so editing a tile through one shows up through the other. What you gain is that a row is an ordinary `int[]`: you can pass it to a method, take `rows[^1]`, slice it into a span, build the whole thing with `[[1, 1], [2], []]`, or swap two rows by swapping two references. ## Choosing for a tile map - A **fixed-size rectangular level**, edited tile by tile and saved as a whole: `int[,]`. The shape enforces the rectangle and `GetLength` gives width and height. - **Rows of different widths** (a staircase-shaped area, per-row chunks streamed from disk) or code that works **row by row** with spans and existing `int[]` APIs: `int[][]`. - Code analysis rule **CA1814** ("Prefer jagged arrays over multidimensional") argues for jagged arrays when a rectangular shape would waste space; it is off by default in .NET 10 and the docs say to suppress it when the multidimensional array wastes nothing. - **Undo snapshots** of the whole map are simplest with `int[,]`, where one `Clone()` is a full copy; with `int[][]` a snapshot must clone every row, or edits will leak into the history. - A single `int[]` indexed as `y * width + x` is the third option; its trade-offs are a data-layout question rather than a C# one.

  • Why does `foreach (int tile in grid)` work on an `int[,]` but `grid.Select(t => t * 2)` does not compile?
    The compiler lowers `foreach` over a multidimensional array into nested loops itself, visiting elements with the rightmost index changing fastest. LINQ's `Select` extends `IEnumerable<T>`, which single-dimensional arrays implement and multidimensional arrays do not, so the SDK reports CS0411 (type arguments cannot be inferred). `grid.Cast<int>().Select(t => t * 2)` adapts it.
  • How do you copy an `int[][]` so that editing the copy never changes the original?
    Copy each row as well as the outer array: `var copy = rows.Select(r => (int[])r.Clone()).ToArray();`, or a loop that clones every row. `rows.Clone()` alone copies only the outer array of references, so both versions share the same rows and a tile edit shows up in both.

  • int[,] and int[][] are two syntaxes for the same type.
  • grid.Length on an int[,] returns the number of rows.
  • new int[3][] creates three empty rows ready to use.
  • You can take a row out of an int[,] with grid[y].
  • Clone on a jagged array makes a full independent copy.