The Analogy: The Numbered Lockers
An array is a row of lockers bolted to a wall. Three things follow from that image, and between them they explain almost every array behaviour in C#.
The lockers are numbered from zero, and the number is not a name you look up — it is a position you walk to. Locker 400 takes exactly as long to reach as locker 0, because the caretaker knows the address arithmetic: start of the row, plus 400 times the locker width.
The lockers are all the same size, which is why an array holds exactly one type. A row of int lockers is four bytes each; a row of string lockers holds addresses, not the strings themselves.
And the row is bolted down. You cannot weld a twenty-first locker onto a row of twenty. Every "growing array" in C# is really a new, longer row plus a removal van — which is precisely what List<T> does for you behind the scenes, and why List<T> is the right choice whenever the count is not known up front.
Syntax or Core Structure
using System;
class Program
{
static void Main()
{
int[] empty = new int[4]; // every slot zeroed
int[] scores = { 88, 72, 95, 61, 79 }; // initialiser sets the length
string[] names = new string[2]; // reference type: nulls
Console.WriteLine($"empty: {string.Join(",", empty)}");
Console.WriteLine($"names: [{names[0] ?? "null"}] [{names[1] ?? "null"}]");
Console.WriteLine($"count {scores.Length}, first {scores[0]}, last {scores[^1]}");
Console.WriteLine($"middle three: {string.Join(",", scores[1..4])}");
Array.Sort(scores);
Console.WriteLine($"sorted: {string.Join(",", scores)}");
Console.WriteLine($"index of 88: {Array.IndexOf(scores, 88)}");
int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } }; // rectangular
Console.WriteLine($"grid {grid.GetLength(0)}x{grid.GetLength(1)}, [1,2] = {grid[1, 2]}");
int[][] jagged = { new[] { 1 }, new[] { 2, 3, 4 } }; // rows of any length
Console.WriteLine($"jagged row lengths: {jagged[0].Length},{jagged[1].Length}");
int total = 0;
foreach (int s in scores) total += s;
Console.WriteLine($"total {total}, mean {(double)total / scores.Length:F1}");
}
}
Output:
empty: 0,0,0,0
names: [null] [null]
count 5, first 88, last 79
middle three: 72,95,61
sorted: 61,72,79,88,95
index of 88: 3
grid 2x3, [1,2] = 6
jagged row lengths: 1,3
total 395, mean 79.0
Note that new int[4] is not "four unset slots" — it is four zeroes. An array is always fully initialised to its element type's default: 0, false, or null. That is why names prints two nulls rather than throwing, and why forgetting to fill an array yields quietly wrong arithmetic rather than a crash.
Technical Depth: Fixed Length, Reference Semantics, and Two Kinds of Grid
An array is a reference type, even when its elements are value types. int[] xs is a variable holding the address of a block on the heap; the block itself carries the length, which is why xs.Length costs nothing and why the runtime can bounds-check every access.
That bounds check is not optional. Reading scores[5] on a five-element array throws IndexOutOfRangeException immediately rather than handing you whatever bytes happen to sit next door — the single most valuable difference between a C# array and a C one.
Length is fixed; Resize is a lie of naming
int[] xs = { 1, 2, 3 };
Array.Resize(ref xs, 5); // note the ref: xs is rebound
Console.WriteLine(string.Join(",", xs)); // 1,2,3,0,0
Array.Resize allocates a new array, copies the elements across and reassigns your variable — which is exactly why it needs ref. Nothing was resized. If you find yourself calling it in a loop, you have written a slower List<T>.
The methods worth memorising
| Call | Effect | Allocates? |
|---|---|---|
Array.Sort(xs) | sorts in place, ascending | no |
Array.Sort(xs, (a, b) => b.CompareTo(a)) | sorts in place with your comparison | no |
Array.Reverse(xs) | reverses in place | no |
Array.IndexOf(xs, v) | first index of v, or -1 | no |
Array.Clear(xs) | resets every slot to its default | no |
Array.Copy(src, dst, n) | copies n elements between arrays | no |
xs.Clone() | new array, same element values | yes |
Array.Empty<int>() | the shared zero-length array | no |
Array.Empty<T>() matters more than it looks: returning new int[0] from a hot method allocates a fresh object every call, and every one of those objects is identical and immutable in practice.
Be clear about what Clone copies. For int[] it is a genuine independent copy. For Order[] it copies the addresses, so both arrays point at the same orders — a shallow copy. Mutating copy[0].Total changes original[0].Total too.
Rectangular versus jagged
int[,] grid (rectangular) | int[][] jagged | |
|---|---|---|
| Shape | every row the same width | each row its own length |
| Memory | one contiguous block | one array of references, plus one array per row |
| Length | grid.Length is the total cell count | jagged.Length is the row count |
| Per-dimension | grid.GetLength(0), GetLength(1) | jagged[r].Length |
| Indexing | grid[r, c] | jagged[r][c] |
| Speed | slightly slower per access, better locality | faster per access, worse locality |
The Length row is the trap. On a 4x5 rectangular array Length is 20, not 4 — so for (int r = 0; r < grid.Length; r++) runs five times too many and throws. Use GetLength(0) for rows.
The covariance hole
Arrays of reference types are covariant, which the type system allows and the runtime then has to police:
object[] items = new string[2]; // compiles: string[] is an object[]
items[0] = 42; // throws ArrayTypeMismatchException
The check happens on every write to a reference-type array, at runtime. List<T> is not covariant and has no such hole, which is one more reason to prefer it.
Slices without copies
scores[1..4] on an array allocates a new array. When you only want to read a window — a parser, a buffer — Span<T> gives you the same window with no allocation at all:
Span<int> window = scores.AsSpan(1, 3);
window[0] = 0; // writes straight into scores[1]
Real World Example: A Seating Chart
A seating plan is the canonical rectangular array: fixed rows, fixed seats per row, every cell the same kind of thing. This program prints the hall, counts the bookings, and finds the longest block of adjacent free seats — the question a box office actually asks.
using System;
class Program
{
const int Rows = 4;
const int Seats = 5;
static readonly string[] RowNames = { "A", "B", "C", "D" };
static void Main()
{
// 0 = free, 1 = booked
int[,] hall =
{
{ 1, 1, 0, 0, 1 },
{ 0, 0, 0, 0, 0 },
{ 1, 1, 1, 1, 1 },
{ 1, 0, 0, 1, 0 },
};
Console.WriteLine(" 1 2 3 4 5");
for (int r = 0; r < Rows; r++)
{
Console.Write($" {RowNames[r]} ");
for (int s = 0; s < Seats; s++)
Console.Write(hall[r, s] == 1 ? "X " : ". ");
Console.WriteLine($" {BookedIn(hall, r)}/{Seats}");
}
int booked = 0;
foreach (int seat in hall) booked += seat; // foreach walks all 20 cells
int capacity = Rows * Seats;
Console.WriteLine($"booked {booked}/{capacity} ({100.0 * booked / capacity:F0}%)");
int[] best = LongestFreeRun(hall);
Console.WriteLine($"longest free run: row {RowNames[best[0]]}, seats {best[1] + 1}-{best[1] + best[2]}");
}
static int BookedIn(int[,] hall, int row)
{
int n = 0;
for (int s = 0; s < hall.GetLength(1); s++) n += hall[row, s];
return n;
}
static int[] LongestFreeRun(int[,] hall)
{
int bestRow = 0, bestStart = 0, bestLen = 0;
for (int r = 0; r < hall.GetLength(0); r++)
{
int run = 0;
for (int s = 0; s < hall.GetLength(1); s++)
{
run = hall[r, s] == 0 ? run + 1 : 0;
if (run > bestLen)
{
bestLen = run;
bestRow = r;
bestStart = s - run + 1;
}
}
}
return new[] { bestRow, bestStart, bestLen };
}
}
Output:
1 2 3 4 5
A X X . . X 3/5
B . . . . . 0/5
C X X X X X 5/5
D X . . X . 3/5
booked 11/20 (55%)
longest free run: row B, seats 1-5
Two techniques here are worth stealing. foreach (int seat in hall) iterates a rectangular array's cells directly, row by row, without any nested loop — ideal when position does not matter and only the total does. And LongestFreeRun never stores the runs it considers: it carries a single run counter that resets to zero on every booked seat, and remembers only the best triple seen so far. The start index falls out as s - run + 1.
The helpers take int[,] hall as an ordinary by-value parameter, and yet they read the caller's grid — the reference-type rule from the previous lesson. They only read it, which is the honest reason no in or ref appears: for an array, by-value already shares the data.
Common Mistakes
- Looping to
xs.Lengthinclusively —for (int i = 0; i <= xs.Length; i++)— and throwingIndexOutOfRangeExceptionon the final pass. The last valid index isLength - 1, orxs[^1]. - Using
grid.Lengthas the row count of anint[,]. It is the total number of cells; you wantgrid.GetLength(0). - Assuming
new string[5]contains five empty strings. It contains five nulls, and the first.Lengthon one of them throws. - Calling
Array.Resizein a loop to grow a collection. Each call allocates and copies the whole array; useList<T>. - Expecting
Clone()on an array of classes to give you independent objects. It copies references — mutate one and both arrays see it. - Adding or removing nothing but still expecting the array to shrink after "deleting" an element. Arrays have no
Remove; you can only overwrite a slot or build a new array. - Assigning into an array through a wider variable (
object[] o = new string[2]; o[0] = 42;) and meetingArrayTypeMismatchExceptionat runtime. - Reaching for
int[,]when the rows are genuinely different lengths. Pad-and-ignore logic spreads through every loop; useint[][]instead.
Best Practices
- Prefer
List<T>whenever the element count is not known in advance; reserve arrays for fixed-size data and hot paths. - Loop with
foreachunless you need the index, and iterate rectangular arrays withGetLength(0)andGetLength(1)rather than hardcoded bounds. - Return
Array.Empty<T>()instead ofnew T[0], and never returnnullwhere an empty array will do. - Use
xs[^1]and range slices for readability, but remember an array slice allocates — reach forAsSpanin tight loops. - Keep
constdimensions (const int Rows = 4;) next to the array so the loops and the declaration cannot drift apart. - Choose
int[][]for ragged data andint[,]for genuine grids; do not simulate one with the other. - Copy explicitly with
Array.CopyorToArray()before handing an array to code you do not control, since by-value passing shares it. - Sort with a comparison delegate rather than writing your own sort loop —
Array.Sort(xs, (a, b) => b.CompareTo(a))is clearer and faster than anything hand-rolled.
Practice Exercises
- Build an
int[12]of monthly rainfall figures, then print the total, the mean to one decimal place, the wettest month by name, and every month above the mean. UseArray.IndexOfon a copy sorted withArray.Sortto find the median as well. - Write
static int[] RemoveAt(int[] xs, int index)that returns a new array with one element gone, usingArray.Copytwice and noList<T>. Prove it works for the first, middle and last positions, and throwArgumentOutOfRangeExceptionwithnameof(index)for anything else. - Represent a 3x3 noughts-and-crosses board as
char[,], fill it from a string of nine characters, print it as a grid, and writestatic char Winner(char[,] board)that checks all three rows, all three columns and both diagonals, returning' 'when there is no winner. Test it with one row win, one diagonal win and one draw. - Create
string[][] timetablewhere each row is one weekday with a different number of lessons. Print each day with its lesson count, then write the same data asstring[5, 4]padded with""and print it too. In three sentences, say which representation you would ship and why.