Autocoder

C# Collections Interview Questions

Last updated 2026-11-19

Collections questions in .NET interviews cover three things: picking the right type for a job, knowing the cost of its operations, and understanding behaviours that cause bugs, such as modifying a list inside a foreach or a ConcurrentDictionary factory running twice.

The answers refer to the System.Collections.Generic types in .NET 8 with C# 12 syntax. LINQ operations over these types are covered on the LINQ page; the Java counterparts are on Java collections.

NamespacesSystem.Collections.Generic, .Concurrent, .Immutable, .Frozen
Language versionC# 12 on .NET 8
FocusComplexity and pitfalls

Choosing a type

C# Collections Interview Questions: questions with worked answers

  1. 1

    How does List<T> grow, and what is the difference between Count and Capacity?

    easy

    List<T> wraps an array. A new empty list has capacity 0; the first Add allocates 4, and each time it is full the capacity doubles (4, 8, 16, ...) and the items are copied. Count is the number of elements used, Capacity is the array length. Set Capacity, pass it to the constructor or call EnsureCapacity when you know the size to avoid repeated copying. Add is amortised O(1), Insert and RemoveAt are O(n).

    csharp
    var list = new List<int>();
    Console.WriteLine(list.Capacity);   // 0
    list.Add(1);
    Console.WriteLine(list.Capacity);   // 4
    for (int i = 0; i < 4; i++) list.Add(i);
    Console.WriteLine(list.Capacity);   // 8  (5 items exceeded 4)
  2. 2

    Explain how Dictionary<TKey, TValue> works internally.

    medium

    It keeps an int array of buckets and an array of entries, each holding the hash code, key, value and a next index. The key hash picks a bucket, and colliding entries are chained through the next field inside the entries array, which is cache friendly. When full it resizes to the next prime size and rehashes. Lookup is O(1) on average and O(n) in the worst case. Keys must have consistent Equals and GetHashCode, and a null key throws.

  3. 3

    Indexer versus Add versus TryGetValue on a Dictionary.

    easy

    The indexer get throws KeyNotFoundException for a missing key, while the indexer set adds or overwrites. Add throws ArgumentException on a duplicate key. TryGetValue returns a bool and the value in one lookup, avoiding double hashing from ContainsKey followed by the indexer. TryAdd inserts only if absent.

    csharp
    var d = new Dictionary<string, int> { ["a"] = 1 };
    d["a"] = 5;                         // overwrite, no exception
    // d.Add("a", 9);                   // ArgumentException
    if (d.TryGetValue("b", out int v)) Console.WriteLine(v);
    else Console.WriteLine("missing");  // missing
    d.TryAdd("b", 2);
  4. 4

    What happens if you modify a List inside a foreach? Compare with Java.

    medium

    The enumerator records the list version and compares it on every MoveNext. Any Add, Remove or Clear changes the version, so the next MoveNext throws InvalidOperationException, even when the removed item was the second-to-last (a case that happens to work in Java). Iterate over a copy, use a reverse for loop, or call RemoveAll with a predicate.

    csharp
    var list = new List<int> { 1, 2, 3, 4 };
    // foreach (var x in list) if (x == 2) list.Remove(x);   // InvalidOperationException
    list.RemoveAll(x => x % 2 == 0);
    Console.WriteLine(string.Join(",", list));    // 1,3
  5. 5

    What is the difference between array, List<T>, IEnumerable<T>, ICollection<T> and IList<T>?

    medium

    An array has a fixed length. List<T> is the resizable implementation. IEnumerable<T> only supports forward iteration, ICollection<T> adds Count, Add, Remove and Contains, and IList<T> adds index access and insertion. IReadOnlyList<T> and IReadOnlyCollection<T> give read-only views. Accept the narrowest interface you need as a parameter and return a concrete or read-only type that fits the contract.

  6. 6

    HashSet<T>, SortedSet<T> and operations on sets.

    medium

    HashSet<T> stores unique items with O(1) average Add and Contains and no order. SortedSet<T> keeps items sorted in a red-black tree with O(log n) operations and range views through GetViewBetween. Both offer UnionWith, IntersectWith, ExceptWith and IsSubsetOf. Add returns false when the item already exists, which is a handy dedupe check.

    csharp
    var seen = new HashSet<int>();
    var unique = new List<int>();
    foreach (var x in new[] { 3, 1, 3, 2, 1 }) if (seen.Add(x)) unique.Add(x);
    Console.WriteLine(string.Join(",", unique));   // 3,1,2
  7. 7

    SortedDictionary versus SortedList versus Dictionary.

    medium

    Dictionary is hash-based with O(1) lookup and unordered enumeration. SortedDictionary is a balanced tree: O(log n) for insert, delete and lookup, using more memory per item. SortedList stores keys and values in two sorted arrays: O(log n) lookup, O(n) insert and delete, but lower memory and fast indexed access, so it suits data that is mostly read and loaded once.

  8. 8

    How does PriorityQueue<TElement, TPriority> behave?

    medium

    Added in .NET 6, it is a binary min-heap: Dequeue returns the element with the lowest priority value first, with O(log n) Enqueue and Dequeue and O(1) Peek. It is not stable, so items with equal priority may come out in any order, and enumerating it does not give sorted order. Use a negated priority or a custom comparer for a max-heap.

    csharp
    var pq = new PriorityQueue<string, int>();
    pq.Enqueue("low", 5);
    pq.Enqueue("urgent", 1);
    pq.Enqueue("mid", 3);
    Console.WriteLine(pq.Dequeue());   // urgent
    Console.WriteLine(pq.Dequeue());   // mid
  9. 9

    Stack<T> and Queue<T>: what do you use them for?

    medium

    Stack<T> is LIFO with Push, Pop and Peek, used for parentheses matching, undo and depth-first search. Queue<T> is FIFO with Enqueue, Dequeue and Peek, used for breadth-first search and work queues. Both are circular-array based with O(1) operations. Pop and Dequeue throw InvalidOperationException on empty; TryPop and TryDequeue return false instead.

  10. 10

    Why can the ConcurrentDictionary.GetOrAdd factory run more than once?

    hard

    GetOrAdd checks for the key, runs your factory outside any lock and then tries to add atomically. If two threads race on a missing key, both factories may run, but only one result is stored and both callers receive that stored value. If the factory has side effects or is expensive, store Lazy<T> values (or use the AsyncLazy pattern) so the real work happens once.

    csharp
    var cache = new ConcurrentDictionary<int, Lazy<string>>();
    string v = cache.GetOrAdd(1, k => new Lazy<string>(() => Expensive(k))).Value;
    static string Expensive(int k) => "v" + k;
  11. 11

    What are the thread-safe collections, and when would you use a Channel?

    medium

    ConcurrentDictionary, ConcurrentQueue, ConcurrentStack and ConcurrentBag support concurrent access without external locks, and BlockingCollection adds blocking and bounding. System.Threading.Channels offers async-friendly producer-consumer pipelines: a Channel<T> can be bounded for back pressure, and reading uses await foreach on ReadAllAsync. Prefer channels over BlockingCollection in async code.

    csharp
    var ch = Channel.CreateBounded<int>(10);
    _ = Task.Run(async () => { for (int i = 0; i < 3; i++) await ch.Writer.WriteAsync(i); ch.Writer.Complete(); });
    await foreach (var x in ch.Reader.ReadAllAsync()) Console.Write(x);   // 012
  12. 12

    What are ReadOnlyCollection, ImmutableArray and FrozenDictionary?

    medium

    ReadOnlyCollection<T> (from AsReadOnly) is a read-only wrapper: changes to the underlying list show through. Types in System.Collections.Immutable, such as ImmutableArray<T> and ImmutableList<T>, never change; every modification returns a new instance, sharing structure when possible. FrozenDictionary and FrozenSet (.NET 8) are built once and optimised for fast reads, ideal for lookup tables created at startup.

    csharp
    using System.Collections.Frozen;
    var fd = new Dictionary<string, int> { ["a"] = 1, ["b"] = 2 }.ToFrozenDictionary();
    Console.WriteLine(fd["b"]);     // 2
  13. 13

    List.Sort versus OrderBy: which is stable?

    hard

    List<T>.Sort and Array.Sort use introsort, which is not stable, so equal elements may be reordered. LINQ OrderBy is stable and returns a new sequence. When sorting by several keys, a single Sort with a comparison delegate or OrderBy with ThenBy is the correct approach. Sort is in place and avoids allocating a new collection.

    csharp
    var people = new List<(string N, int Age)> { ("a", 30), ("b", 25), ("c", 30) };
    people.Sort((x, y) => x.Age.CompareTo(y.Age));   // may reorder a and c
    var stable = people.OrderBy(p => p.Age).ToList();
  14. 14

    What does a custom key need to work in a Dictionary or HashSet?

    medium

    Equals and GetHashCode must agree: equal keys must return equal hash codes, and the hash must not change while the key is in the collection. Use readonly structs or records for composite keys, or pass an IEqualityComparer<T>, for example StringComparer.OrdinalIgnoreCase for case-insensitive text keys.

    csharp
    var d = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase) { ["Key"] = 1 };
    Console.WriteLine(d["KEY"]);      // 1
    var grid = new HashSet<(int X, int Y)> { (1, 2) };
    Console.WriteLine(grid.Contains((1, 2)));  // True
  15. 15

    When would you use LinkedList<T>?

    easy

    LinkedList<T> is a doubly linked list with O(1) insertion and removal once you hold a node, but O(n) search and no index access, and each node is a separate heap object, so it is slower than List<T> for most workloads. It fits LRU caches and algorithms that splice nodes. Otherwise prefer List<T>, Queue<T> or a Deque built on arrays.

  16. 16

    How do collection expressions and spans change collection code in C# 12?

    medium

    Collection expressions ([1, 2, 3], [..a, ..b]) create arrays, lists, spans and other collection types from one syntax, and the compiler picks an efficient construction. Span<T> and ReadOnlySpan<T> let you slice arrays, strings and stack memory without copying, and CollectionsMarshal.AsSpan gives direct access to a list's backing array for hot loops, at the price of invalidation if the list grows.

    csharp
    List<int> a = [1, 2, 3];
    int[] b = [..a, 4];
    ReadOnlySpan<int> slice = b.AsSpan(1, 2);
    Console.WriteLine(slice[0]);   // 2

Frequently asked questions

What is the most common C# collections question?

Dictionary internals, List versus array, IEnumerable versus IList and why a foreach cannot modify its list.

Is Dictionary thread safe?

No. Concurrent writes can corrupt it; use ConcurrentDictionary or a lock.

What is the difference between Hashtable and Dictionary?

Hashtable is non-generic and boxes keys and values; Dictionary<TKey, TValue> is generic, faster and type safe.

Where can I practise problems using these types?

Try C# coding questions and the DSA hub.

Related guides

More in Programming Language Interview Questions by Language

See all in this section