skip to content

Collection Types

Arrays, List<T>, Dictionary<TKey,TValue>, HashSet<T>, queues and the concurrent, immutable and frozen variants. Interviewers ask which collection fits an access pattern.

on this pageshow

explore

questions

page 1 of 2

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

With C#'s Dictionary<TKey,TValue>, what does the indexer do for a missing key, and when do TryGetValue, TryAdd and Add fit better?

level: juniorimportance: must knowfreq 78%

basics

~20 s

Reading a missing key through Dictionary<TKey,TValue>'s indexer throws KeyNotFoundException; writing through it adds or silently overwrites. Use TryGetValue when absence is normal, Add when a duplicate is a bug, and TryAdd to insert only if absent.

open as a page

In C#, what may a caller do through IEnumerable<T>, ICollection<T>, IList<T>, IReadOnlyCollection<T> and IReadOnlyList<T>, and which should a parameter use?

level: juniorimportance: must knowfreq 70%

basics

~10 s

IEnumerable<T> only enumerates; IReadOnlyCollection<T> adds Count; IReadOnlyList<T> adds a get-only indexer; ICollection<T> adds Count, Add, Remove and Clear; IList<T> adds an indexer setter, Insert and RemoveAt. A parameter takes the least its method uses.

open as a page

In C#, how do Queue<T> and Stack<T> differ in removal and enumeration order, and what happens when you Dequeue or Pop an empty one?

level: juniorimportance: must knowfreq 62%

basics

~10 s

Queue<T> is first-in-first-out (Enqueue, Dequeue) and Stack<T> is last-in-first-out (Push, Pop); foreach walks each in that removal order. Dequeue, Pop and Peek on an empty one throw InvalidOperationException; TryDequeue, TryPop and TryPeek return false.

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 .NET, can ConcurrentDictionary<TKey,TValue>.GetOrAdd run its value factory more than once for the same key, and how do you make it run once?

level: middleimportance: must knowfreq 50%

basics

~20 s

Yes. GetOrAdd runs the factory outside the dictionary's lock, so threads that miss at the same moment can each run it; one result is stored and every caller receives that one. Store Lazy<TValue> values to make the expensive work run once.

open as a page

A C# Course class returns its private List<Student> as IReadOnlyList<Student>; how can a caller still add students, and how do you stop it?

level: middleimportance: must knowfreq 60%

basics

~10 s

Returning the list through IReadOnlyList<Student> narrows only the reference; the object is still the List<Student>, so a caller can cast it back and call Add. Return a ReadOnlyCollection<Student> wrapper from AsReadOnly() instead.

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 .NET, how do ConcurrentQueue<T>, ConcurrentStack<T> and ConcurrentBag<T> differ, and when is ConcurrentBag<T> the right choice?

level: middleimportance: should knowfreq 35%

basics

~20 s

ConcurrentQueue<T> is first-in first-out and ConcurrentStack<T> last-in first-out. ConcurrentBag<T> promises no order: each thread keeps its own list and steals from others only when that is empty, so it pays off when the same threads both add and take.

open as a page

In C#, how do you key a Dictionary<TKey,TValue> or HashSet<T> by a class you cannot modify that only has reference equality?

level: middleimportance: should knowfreq 48%

basics

~10 s

Write an IEqualityComparer<T> whose Equals and GetHashCode use the identifying fields and pass it to the Dictionary<TKey,TValue> or HashSet<T> constructor; every lookup then hashes and compares keys through it instead of reference equality.

open as a page

In C#, what do HashSet<T>'s UnionWith, IntersectWith and ExceptWith do to the set you call them on, and how do SetEquals and IsSubsetOf compare?

level: middleimportance: should knowfreq 45%

basics

~20 s

UnionWith, IntersectWith and ExceptWith mutate the HashSet<T> they are called on and return void, so copy the set first if you still need it. SetEquals and IsSubsetOf only test, ignoring order and duplicates in the other collection.

open as a page

In .NET, why must code not rely on Dictionary<TKey,TValue> enumeration order, and when does OrderedDictionary<TKey,TValue> or SortedDictionary<TKey,TValue> fit instead?

level: middleimportance: should knowfreq 38%

basics

~10 s

Dictionary<TKey,TValue> promises no enumeration order, and after a Remove the next insertion reuses the freed slot mid-sequence. OrderedDictionary<TKey,TValue> (.NET 9) keeps insertion order with index access; SortedDictionary<TKey,TValue> keeps key order.

open as a page

In .NET, why does building an ImmutableArray<T> with Add in a loop allocate far more than ImmutableList<T>, and how do builders fix it?

level: middleimportance: should knowfreq 38%

basics

~20 s

ImmutableArray<T> wraps one array, so every Add copies all elements into a new array; ImmutableList<T> is a balanced tree, so Add copies only one path of nodes. For bulk construction, fill a mutable builder and convert it once with ToImmutable or MoveToImmutable.

open as a page

In C#, why does rules.Add("gbp-rounding") leave an ImmutableList<string> unchanged, and how do you fix the code?

level: middleimportance: should knowfreq 45%

basics

~10 s

ImmutableList<T>.Add never changes the list it is called on; it returns a new ImmutableList<T> containing the item. Code that ignores the return value throws the new list away. Assign it: rules = rules.Add("gbp-rounding").

open as a page

In .NET, what does each promise when a pricing service hands out flags as a ReadOnlyCollection<T>, an ImmutableList<T> or a FrozenSet<T>?

level: middleimportance: should knowfreq 48%

basics

~20 s

A ReadOnlyCollection<T> is a read-only view: callers cannot change it, but the owner's list still can. An ImmutableList<T> is a copy nobody can change; changes return new versions. A FrozenSet<T> (.NET 8) is also unchangeable, built once for fast lookups.

open as a page

In C#, an int[] seen as ICollection<int> reports IsReadOnly true, yet IList<int>'s indexer still writes to it; what do IsReadOnly and NotSupportedException tell a caller?

level: middleimportance: should knowfreq 30%

basics

~10 s

ICollection<T>.IsReadOnly is the run-time hint that Add, Remove and Clear will throw NotSupportedException. An array reports true because its size is fixed, yet IList<T>'s indexer setter still replaces elements; ReadOnlyCollection<T> rejects every write.

open as a page

How do .NET's Queue<T> and Stack<T> store items internally, and what does Enqueue or Push cost when the backing array is full?

level: middleimportance: should knowfreq 34%

basics

~20 s

Stack<T> fills a T[] upward from index 0; Queue<T> treats a T[] as a circular buffer with wrapping head and tail indexes. When full, each allocates a double-size array and copies, so adds are amortized O(1).

open as a page

In .NET's PriorityQueue<TElement,TPriority>, which item does Dequeue return first, what order do equal priorities come out in, and can you foreach over it?

level: middleimportance: should knowfreq 42%

basics

~20 s

Dequeue returns the element with the lowest priority under the queue's IComparer<TPriority>. Equal priorities come out in no guaranteed order, and the class has no GetEnumerator, so foreach fails with CS1579; UnorderedItems walks the heap unsorted.

open as a page

With a .NET ConcurrentDictionary<string, int>, why does `counters[t] = counters.GetValueOrDefault(t) + 1` lose counts, and when is a lock still needed?

level: seniorimportance: should knowfreq 45%

basics

~20 s

The read and the write are separate thread-safe calls, so two threads can both read 7 and both write 8. AddOrUpdate retries its delegate until a compare-and-swap succeeds; a lock is still needed when one rule spans several keys or collections.

open as a page

A C# gateway shares one Dictionary<string, int> of rate-limit counters across request threads without a lock; what can concurrent writes do, and are concurrent reads safe?

level: seniorimportance: should knowfreq 42%

basics

~10 s

Concurrent writes can corrupt Dictionary<TKey,TValue>: entries vanish silently, or calls throw exceptions such as IndexOutOfRangeException or InvalidOperationException. Concurrent reads are safe only while no thread writes. Use ConcurrentDictionary, or one lock around every access.

open as a page

A hot C# loop updates a Dictionary<TKey,TValue> with ContainsKey and then the indexer — how do you cut the repeated lookups, and what makes CollectionsMarshal.GetValueRefOrAddDefault risky?

level: seniorimportance: should knowfreq 32%

basics

~20 s

ContainsKey plus the indexer hashes the key twice, three times for read-modify-write. Use TryGetValue or TryAdd for one lookup, or CollectionsMarshal.GetValueRefOrAddDefault to update in place, but never add or remove entries while holding that ref.

open as a page

In .NET, how do SortedDictionary<TKey,TValue> and SortedList<TKey,TValue> differ in structure, insertion cost, memory and index access, and when does each win?

level: seniorimportance: should knowfreq 34%

basics

~20 s

SortedDictionary<TKey,TValue> is a red-black tree: O(log n) insert and remove, one node object per entry, no index access. SortedList<TKey,TValue> is two sorted arrays: O(log n) lookup, O(n) insert or remove except at the end, less memory, index access.

open as a page

In C#, why does reading Length on an ImmutableArray<decimal> property that was never assigned throw NullReferenceException, and how do you guard against it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

ImmutableArray<T> is a struct wrapping an array, and its default value wraps null. Length, the indexer, Add and foreach use that null array and throw NullReferenceException. Initialise to ImmutableArray<T>.Empty or [], and test IsDefault at boundaries.

open as a page

In .NET 8 and later, a pricing service freezes its case-insensitive currency table with loaded.ToFrozenDictionary(), and lookups of "usd" now miss; why, and when is freezing worth it?

level: seniorimportance: should knowfreq 40%

basics

~10 s

ToFrozenDictionary uses EqualityComparer<TKey>.Default unless you pass a comparer, so freezing a case-insensitive Dictionary without one rebuilds it case-sensitively. Pass StringComparer.OrdinalIgnoreCase. Freezing pays off for tables built once and read constantly.

open as a page

A C# report keeps the ReadOnlyCollection<Student> that Course.Students returned, and its Count later changes; why, and when should Course return a copy?

level: seniorimportance: should knowfreq 42%

basics

~20 s

ReadOnlyCollection<T> is a live view: it holds a reference to the owner's list and forwards every read, so later enrolments show through it. Return a copy, such as ToArray(), when a caller needs a stable snapshot.

open as a page

A C# print scheduler marks a queued job as rush by calling Enqueue again on its PriorityQueue<string,int>, and the job prints twice; why, and how do you fix it?

level: seniorimportance: should knowfreq 28%

basics

~10 s

PriorityQueue<TElement,TPriority> has no update-priority member, so a second Enqueue adds another pair and the old one stays queued. Track each job's current priority and skip stale pairs on dequeue, or remove and rebuild.

open as a page

As a C# lead, would you make ConcurrentDictionary or a lock around Dictionary<TKey,TValue> the team default for shared mutable maps, and why?

level: principalimportance: should knowfreq 30%

basics

~20 s

Default to ConcurrentDictionary for maps that many threads read and update one key at a time. Choose a lock around a plain Dictionary when an operation spans several entries, needs a consistent snapshot, or the map is small and rarely touched.

open as a page

Should a .NET team standardise on immutable collections for shared state like a pricing service's rules snapshot, and what does that standard cost?

level: principalimportance: should knowfreq 30%

basics

~20 s

Often yes for read-mostly shared state: readers get lock-free snapshots and writers publish new versions with ImmutableInterlocked.Update. The costs are an allocation per change, slower lookups than Dictionary and new bug patterns, so write-heavy and startup-only state need other choices.

open as a page

showing 1–30 of 35