Search⌘ K
AI Features

Working with Immutable Collections

Explore how to create and use immutable collections in C# by leveraging the System.Collections.Immutable namespace. Understand the benefits of immutability for thread safety and performance, and learn techniques to process collections efficiently while avoiding common pitfalls related to deferred execution and memory allocation.

Sometimes, we need to make a collection immutable, meaning that its members cannot change, i.e. we cannot add or remove them. If we import the System.Collections.Immutable namespace, then any collection that implements IEnumerable is given six extension methods to convert it into an immutable list, dictionary, hashset, and so on.

Creating an immutable list in C#

Let’s see a simple example of converting the cities list into an immutable list:

Step 1: In the WorkingWithCollections ...