Working with Immutable Collections
Learn about creating immutable collections and the benefits of using concrete types.
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
project, in Program.cs
, import the System.Collections.Immutable
namespace.
Step 2: In Program.cs
, add statements to convert the cities list into an immutable list, and then add a new city to it, as shown in the following code:
Get hands-on with 1400+ tech skills courses.