C# Collections: Which One to Use and When

A collection holds a group of objects and, unlike an array, grows and shrinks as you add and remove items. .NET ships a dozen of them, and choosing the right one usually comes down to a single question: how will you look items up?

All the types you should reach for live in System.Collections.Generic and are typed: a List<string> only accepts strings, and reading from it needs no cast. The older types in System.Collections (ArrayList, Hashtable and the non-generic Queue and Stack) store everything as object and date from .NET 1.0. They still work, but new code has no reason to use them.

The everyday collections

List<string> names = ["Ada", "Grace", "Linus"];
names.Add("Barbara");
Console.WriteLine(names[1]);              // Grace

var stock = new Dictionary<string, int>
{
    ["apples"] = 12,
    ["pears"] = 3
};
if (stock.TryGetValue("pears", out int pears))
    Console.WriteLine(pears);             // 3

HashSet<string> tags = ["csharp", "dotnet"];
Console.WriteLine(tags.Add("csharp"));    // False, it is already there

var queue = new Queue<string>();
queue.Enqueue("first");
queue.Enqueue("second");
Console.WriteLine(queue.Dequeue());       // first

var stack = new Stack<string>();
stack.Push("first");
stack.Push("second");
Console.WriteLine(stack.Pop());           // second

The square-bracket syntax is a collection expression (C# 12). It works for lists, arrays, sets and spans; dictionaries still use an initializer.

Choosing one

TypeUse it forLookup cost
List<T>An ordered list you read by index or loop overO(1) by index, O(n) for Contains
Dictionary<TKey, TValue>Finding a value by keyO(1) on average
HashSet<T>Unique items and fast “is it in there?” checksO(1) on average
Queue<T>First in, first out: work items, breadth-first searchO(1) to add and remove
Stack<T>Last in, first out: undo history, parsing, depth-first searchO(1) to push and pop
PriorityQueue<TElement, TPriority>Always taking the most urgent item next (.NET 6+)O(log n) to add and remove
SortedDictionary<TKey, TValue>Key lookup with keys kept in orderO(log n)
SortedSet<T>Unique items kept in order, range queriesO(log n)
LinkedList<T>Frequent inserts and removals in the middle, when you hold the nodeO(1) insert, O(n) search

List<T> is the right default far more often than not. A common mistake is calling list.Contains inside a loop over another list: that is O(n × m), and switching the inner list to a HashSet<T> makes it O(n). LinkedList<T> sounds attractive for inserts, but its poor memory locality means a List<T> is usually faster in practice unless the list is large and you already hold a reference to the node.

Thread safety

None of the collections above are safe to modify from several threads at once. Concurrent reads are fine as long as nobody writes. When threads share a collection, use the types in System.Collections.Concurrent: ConcurrentDictionary<TKey, TValue>, ConcurrentQueue<T> and ConcurrentStack<T>. For producer and consumer pipelines, System.Threading.Channels is often a better fit than a concurrent queue, because consumers can await new items instead of polling.

Read-only, immutable and frozen

Exposing a List<T> from a class lets callers change it behind your back. There are three levels of protection:

  • Read-only views such as ReadOnlyCollection<T> (from list.AsReadOnly()) block changes through the view, but the owner can still change the list underneath.
  • Immutable collections in System.Collections.Immutable (ImmutableList<T>, ImmutableDictionary<TKey, TValue>) never change; every “modification” returns a new collection.
  • Frozen collections (FrozenDictionary<TKey, TValue> and FrozenSet<T>, .NET 8+) are built once and tuned for fast reads. They suit lookup tables that are filled at startup and read for the rest of the process’s life.

Interfaces for parameters and return types

Accept the least specific interface you need and return something honest. A method that only loops over its input should take IEnumerable<T>. One that needs the count or index access can take IReadOnlyList<T> or IReadOnlyCollection<T>. Returning IReadOnlyList<T> tells callers they get a finished list they should not modify, which is clearer than returning a lazy IEnumerable<T> that may run a query every time it is enumerated.

Related examples

Leave a Comment