Arrays: The Locker Room

Arrays: The Locker Room in C#: An array is a row of lockers bolted to a wall. Three things follow from that image, and between them they explain almost every…

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

CallEffectAllocates?
Array.Sort(xs)sorts in place, ascendingno
Array.Sort(xs, (a, b) => b.CompareTo(a))sorts in place with your comparisonno
Array.Reverse(xs)reverses in placeno
Array.IndexOf(xs, v)first index of v, or -1no
Array.Clear(xs)resets every slot to its defaultno
Array.Copy(src, dst, n)copies n elements between arraysno
xs.Clone()new array, same element valuesyes
Array.Empty<int>()the shared zero-length arrayno

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
Shapeevery row the same widtheach row its own length
Memoryone contiguous blockone array of references, plus one array per row
Lengthgrid.Length is the total cell countjagged.Length is the row count
Per-dimensiongrid.GetLength(0), GetLength(1)jagged[r].Length
Indexinggrid[r, c]jagged[r][c]
Speedslightly slower per access, better localityfaster 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

  1. Looping to xs.Length inclusively — for (int i = 0; i <= xs.Length; i++) — and throwing IndexOutOfRangeException on the final pass. The last valid index is Length - 1, or xs[^1].
  2. Using grid.Length as the row count of an int[,]. It is the total number of cells; you want grid.GetLength(0).
  3. Assuming new string[5] contains five empty strings. It contains five nulls, and the first .Length on one of them throws.
  4. Calling Array.Resize in a loop to grow a collection. Each call allocates and copies the whole array; use List<T>.
  5. Expecting Clone() on an array of classes to give you independent objects. It copies references — mutate one and both arrays see it.
  6. 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.
  7. Assigning into an array through a wider variable (object[] o = new string[2]; o[0] = 42;) and meeting ArrayTypeMismatchException at runtime.
  8. Reaching for int[,] when the rows are genuinely different lengths. Pad-and-ignore logic spreads through every loop; use int[][] 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 foreach unless you need the index, and iterate rectangular arrays with GetLength(0) and GetLength(1) rather than hardcoded bounds.
  • Return Array.Empty<T>() instead of new T[0], and never return null where an empty array will do.
  • Use xs[^1] and range slices for readability, but remember an array slice allocates — reach for AsSpan in tight loops.
  • Keep const dimensions (const int Rows = 4;) next to the array so the loops and the declaration cannot drift apart.
  • Choose int[][] for ragged data and int[,] for genuine grids; do not simulate one with the other.
  • Copy explicitly with Array.Copy or ToArray() 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

  1. 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. Use Array.IndexOf on a copy sorted with Array.Sort to find the median as well.
  2. Write static int[] RemoveAt(int[] xs, int index) that returns a new array with one element gone, using Array.Copy twice and no List<T>. Prove it works for the first, middle and last positions, and throw ArgumentOutOfRangeException with nameof(index) for anything else.
  3. Represent a 3x3 noughts-and-crosses board as char[,], fill it from a string of nine characters, print it as a grid, and write static 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.
  4. Create string[][] timetable where each row is one weekday with a different number of lessons. Print each day with its lesson count, then write the same data as string[5, 4] padded with "" and print it too. In three sentences, say which representation you would ship and why.