C# Interview Question #129

What are immutable collections in .NET?

Advanced LINQ, Expressions & Collections Senior Advanced

Quick Interview Answer

Immutable collections create a new collection when a change is requested rather than modifying the existing instance.

Detailed Explanation

Immutable collections create a new collection when a change is requested rather than modifying the existing instance.

The System.Collections.Immutable package provides types such as ImmutableList<T>, ImmutableDictionary<TKey,TValue>, and ImmutableHashSet<T>.

They can simplify concurrency and state management because an existing collection cannot be changed unexpectedly by another part of the program. They are useful for shared configuration, snapshots, functional-style designs, and other scenarios where immutability is valuable.

They are not automatically the best choice for every collection because repeated modifications can have different performance characteristics from mutable collections.

Code Example

ImmutableList<string> original =
    ImmutableList.Create("A", "B");

ImmutableList<string> updated =
    original.Add("C");

// original still contains only A and B.