The System.Collections.Immutable
NuGet package provides immutable collection classes.
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
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
builder.Add(1);
builder.Add(2);
var list = builder.ToImmutable();
var numbers = Enumerable.Range(1, 5);
var list = ImmutableList.CreateRange<int>(numbers);
List of all immutable collection types:
System.Collections.Immutable.ImmutableArray<T>
System.Collections.Immutable.ImmutableDictionary<TKey,TValue>
System.Collections.Immutable.ImmutableHashSet<T>
System.Collections.Immutable.ImmutableList<T>
System.Collections.Immutable.ImmutableQueue<T>
System.Collections.Immutable.ImmutableSortedDictionary<TKey,TValue>
System.Collections.Immutable.ImmutableSortedSet<T>
System.Collections.Immutable.ImmutableStack<T>