Immutable collections in .NET

July 30, 2015
Dealing with immutable collections in .NET  is very easy with the help of the ImmutableCollections package on nuget .

Here's a example :

ImmutableList initial = ImmutableList.Empty;
ImmutableList immutableList = initial.Add("stuff");


Any operation on the collection will create a duplicate collection (so in the above example the "initial" collection is still empty).
Another much simple way would to be use the IReadCollection from .NET 4.5
List initial = Enumerable.Range(1, 10).ToList();
ReadOnlyCollection readOnlyCollection = initial.AsReadOnly();

Now you can pass readOnlyCollection and obviously the initial collection will remain unchanged.




© Marius Gheorghe