skip to content

Arrays and Lists

Arrays have a fixed length, List<T> grows by reallocating, and collection expressions with Index and Range build and slice both. Interviewers ask about capacity and copies.

on this pageshow

explore

questions

6

In C#, what do `history[^1]` and `history[1..^1]` return for a `string[]` and for a `List<string>`, and is the range a copy?

level: juniorimportance: must knowfreq 60%

answer

  1. counting from the end
  2. ^0 sits one past the end
  3. start inclusive, end exclusive
  4. GetSubArray for arrays, Slice for lists

basics

~20 s

history[^1] is the last element in both cases. history[1..^1] drops the first and last elements and returns a copy: a new string[] from the array, a new List<string> from the list, so editing it leaves history unchanged.

solid answer

~40 s

`^1` is a `System.Index` counted from the end, so `history[^1]` means `history[history.Length - 1]` on the array and `history[history.Count - 1]` on the `List<string>`. `^0` is one past the end and throws: `IndexOutOfRangeException` on the array, `ArgumentOutOfRangeException` on the list. `1..^1` is a `System.Range` with an inclusive start and an exclusive end, so it skips the first and the last element. On an array the compiler calls `RuntimeHelpers.GetSubArray`, which allocates a new array and copies; on a `List<T>` it calls `List<T>.Slice(int, int)`, which calls `GetRange` and returns a new list. Both results are shallow copies, so writing to them never reaches `history`. When you need a view instead of a copy, slice a span such as `history.AsSpan(1..^1)`.

code

csharp · 17 lines
csharp
string[] history = ["paint", "erase", "place", "move", "rotate"];
Console.WriteLine(history[^1]);                      // rotate
Console.WriteLine(string.Join(",", history[1..^1])); // erase,place,move

string[] tail = history[^2..];    // RuntimeHelpers.GetSubArray: a new string[2]
tail[0] = "CHANGED";
Console.WriteLine(history[^2]);   // move: the original is untouched

var list = new List<string>(history);
List<string> listTail = list[^2..]; // binds to List<T>.Slice, which calls GetRange
listTail[0] = "CHANGED";
Console.WriteLine(list[^2]);      // move

try { _ = history[^0]; }
catch (IndexOutOfRangeException) { Console.WriteLine("history[^0] is one past the end"); }
try { _ = list[^0]; }
catch (ArgumentOutOfRangeException) { Console.WriteLine("list[^0] is one past the end"); }

go deeper

for a junior

Know that ^1 is the last element and ^0 is past the end, and that a range has an inclusive start and an exclusive end. Say plainly that the range gives you a new array or list.

for a middle

Explain what the compiler emits: an index from the end becomes Length or Count minus n, an array range calls RuntimeHelpers.GetSubArray, and a list range calls Slice, which is GetRange. Point out that both copy.

for a senior

Spot the hidden allocation when a range sits in a per-frame or per-request loop, and replace it with a span slice or with RemoveRange when the intent was to shorten the list. Know which exception each misuse throws.

for a principal

Treat ranges as a readability tool with a copy cost, and set a team expectation that hot paths slice spans while ordinary code may use ranges freely; the review question is always whether a copy was intended.

## Index and Range in C# C# 8 added two operators, backed by two small library types, for addressing positions in a sequence: - **`System.Index`** is a position that can count from the start or from the end. The **hat operator** `^n` builds an index *from the end*: `^1` is the last element, `^2` the one before it, and `^0` is the position *one past* the last element. - **`System.Range`** is a pair of indexes written with the **range operator** `..`. Its start is **inclusive** and its end is **exclusive**, so `1..3` holds positions 1 and 2. Either side may be left out: `..2` starts at 0, `2..` runs to the end, `..` is everything. Both are ordinary structs, so you can store them and pass them around: `Index last = ^1; Range middle = 1..^1;`. `Index.FromEnd(1)` and `Range.StartAt(2)` build the same values without the operators, and `Range.GetOffsetAndLength(int length)` converts a range into a concrete start and length for a sequence of that length, which is what your own APIs need when they accept a `Range` parameter. ## What the compiler turns them into Most types never declare an `Index` or `Range` indexer. The compiler supplies one when the type is **countable** (it has an `int` `Length` or `Count`) and has the right members: 1. For `x[^1]` it needs an `int` indexer, and rewrites the access as `x[x.Length - 1]` (or `x.Count - 1`). 2. For `x[1..^1]` it needs a `Slice(int start, int length)` method, and computes the start and the length itself before calling it. 3. Arrays and strings are special-cased: an array range calls `RuntimeHelpers.GetSubArray<T>(T[], Range)` and a string range calls `Substring`. | Expression | `string[] history` | `List<string> history` | |---|---|---| | `history[^1]` | `history[history.Length - 1]` | `history[history.Count - 1]` | | `history[^0]` | throws `IndexOutOfRangeException` | throws `ArgumentOutOfRangeException` | | `history[1..^1]` | `RuntimeHelpers.GetSubArray`: a new `string[]` | `history.Slice(1, Count - 2)`: a new `List<string>` | `List<T>` gets range support only because it has a public `Slice(int, int)` method, and in the reference source that method is one line: `=> GetRange(start, length)`. ## Copies, not views The most common misunderstanding is that a range is a window onto the original. It is not, for either type: - `GetSubArray` allocates a **new array** of the slice's length and copies the elements into it (an empty range returns `Array.Empty<T>()`). - `GetRange` allocates a **new `List<T>`** with exactly that capacity and copies the elements with `Array.Copy`. - The copy is **shallow**: for a list of class instances both lists point at the same objects, so mutating an object is visible through both, while replacing or clearing an element in the copy is not. When you want to read or write part of an array without copying, take a span instead, as in `history.AsSpan(1..^1)`; slicing spans is its own subject, covered with `Span<T>`. ## Edge cases and exceptions The rules for which exception you get differ between the two types, because the compiler lowers them differently: - `^0` is one past the end on any type: an array throws `IndexOutOfRangeException`, a `List<T>` throws `ArgumentOutOfRangeException` from its indexer. - `^1` on an empty `List<T>` becomes `list[-1]` and throws `ArgumentOutOfRangeException`. - A range that runs past the end of an array, such as `history[3..10]` on five elements, throws `ArgumentOutOfRangeException` from `Range.GetOffsetAndLength`. - The same range on a `List<T>` throws **`ArgumentException`**: the compiler passes `Slice(3, 7)` straight through, and `GetRange` reports an invalid offset and length. - A reversed range such as `4..2` gives a negative length and throws `ArgumentOutOfRangeException` on both. - `history[..0]` and `history[^0..]` are legal and return empty copies. ## In the level editor's undo history An editor keeps its undo steps in a `List<EditorAction>`, newest last, so `undo[^1]` is the step to undo next and `undo[^3..]` is the three most recent steps, for a tooltip, as a separate list. What a range cannot do is shorten the list. `undo = undo[..^2]` builds a new list and leaves the old one for the garbage collector; `undo.RemoveRange(undo.Count - 2, 2)` removes the two newest steps in place and keeps the list's capacity for the next edits. Reach for a range when you want a copy, and for `RemoveRange` or `RemoveAt(undo.Count - 1)` when you want the list itself to change.

  • Why does `list[3..10]` on a five-element `List<T>` throw `ArgumentException`, while the same range on an array throws `ArgumentOutOfRangeException`?
    The lowering differs. For a list the compiler computes the start (3) and the length (10 - 3 = 7) itself and calls `Slice(3, 7)`, which calls `GetRange`; `GetRange` sees that 3 + 7 runs past `Count` and throws `ArgumentException` for an invalid offset and length. For an array, `RuntimeHelpers.GetSubArray` calls `Range.GetOffsetAndLength`, which validates the range and throws `ArgumentOutOfRangeException`.
  • How do you drop the two newest undo steps from a `List<T>` without allocating a new list?
    Call `undo.RemoveRange(undo.Count - 2, 2)`. It removes the elements in place and keeps the backing array, so the next edits reuse its capacity. `undo = undo[..^2]` looks shorter but calls `Slice`, which allocates a new list, copies the remaining elements and leaves the old list for the garbage collector.
  • Which of your own types get `^1` and `..` without declaring an `Index` or `Range` indexer?
    A countable type, one with an `int` `Length` or `Count` property, gets `x[^1]` if it has an `int` indexer, and gets `x[a..b]` if it also has a `Slice(int, int)` method. The compiler rewrites the expressions into calls on those members, so the range returns whatever your `Slice` returns, a copy or a view.

  • ^0 is the last element, just as index 0 is the first.
  • A range on an array returns a view that writes back to the original.
  • Ranges only work on arrays and strings, never on a List<T>.
  • The end of a range is inclusive, so 1..3 holds three elements.
  • Assigning undo = undo[..^2] trims the existing list in place.
open as a page

In C#, an array's length is fixed, so how does `List<T>` grow on `Add`, and what do `Count`, `Capacity` and `EnsureCapacity` control?

level: middleimportance: must knowfreq 70%

basics

~20 s

List<T> stores its items in an array: Count is how many it holds, Capacity is that array's length. An Add with no room allocates an array twice as long (four at first) and copies everything; a capacity hint avoids those copies.

open as a page

In C# 12, what does `[..groundRow, ..wallRow, 0]` create when it is assigned to an `int[]`, a `List<int>` and an `IEnumerable<int>`?

level: middleimportance: should knowfreq 45%

basics

~20 s

A new collection of the target's type holding groundRow's elements, then wallRow's, then 0: a new int[], a new List<int> sized to fit, or a read-only collection the compiler synthesizes for IEnumerable<int>. The spread copies elements immediately.

open as a page

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%

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.

open as a page

Why can `List<T>.Sort` in C# reorder entities that compare equal, and how do you sort them by layer while keeping placement order?

level: middleimportance: should knowfreq 40%

basics

~20 s

List<T>.Sort runs the same introspective sort as Array.Sort, which is unstable: elements that compare equal may come out in any relative order. Keep placement order with Enumerable.OrderBy, which is stable, or add the original index as a tiebreaker.

open as a page

In C#, a level editor takes `CollectionsMarshal.AsSpan(placed)` on a `List<Placement>`, keeps adding entities, and some position writes through the span never appear; why, and what fixes it?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

The span covers the list's backing array as it was when AsSpan ran. An Add beyond Capacity moves the items to a new array, so later writes silently hit the old one. Take the span after the last Add or Remove.

open as a page