C# Language Immutable collections


The System.Collections.Immutable NuGet package provides immutable collection classes.

Creating and adding items

var stack = ImmutableStack.Create<int>();
var stack2 = stack.Push(1); // stack is still empty, stack2 contains 1
var stack3 = stack.Push(2); // stack2 still contains only one, stack3 has 2, 1

Creating using the builder

Certain immutable collections have a Builder inner class that can be used to cheaply build large immutable instances:

var builder = ImmutableList.CreateBuilder<int>(); // returns ImmutableList.Builder
var list = builder.ToImmutable();

Creating from an existing IEnumerable

var numbers = Enumerable.Range(1, 5);
var list = ImmutableList.CreateRange<int>(numbers);

List of all immutable collection types: