ImmutableList
Code often acts on Lists under the assumption that the elements in the List
will not be changed. But occasionally a mistake is made and the List
is changed unexpectedly.
This can cause problems and incorrect program output. It is possible to ensure the List
is never changed throughout runtime by using ImmutableList
instead.
In .NET we find many immutable collections, not just ImmutableList
but also ImmutableArray
and ImmutableDictionary
. None of them can be modified at runtime.
class
. The readonly
keyword ensures the field reference is also not changed.Length
property on an ImmutableArray
. It is also possible to loop over the elements with foreach
, just like other arrays.ImmutableList
can be accessed and enumerated
like other Lists.ImmutableDictionary
.ImmutableList
, the method creates a modified copy of the underlying data and returns the copy.using System; using System.Collections.Generic; using System.Collections.Immutable; class Program { // Part 1: use immutable collections as fields. static readonly ImmutableArray<string> _colors = ["blue", "aqua", "cerulean"]; static readonly ImmutableList<int> _sizes = [10, 20, 15, 0]; static readonly ImmutableDictionary<string, bool> _items = ImmutableDictionary.CreateRange( [KeyValuePair.Create("computer", true), KeyValuePair.Create("desk", false), KeyValuePair.Create("monitor", true)]); public static void Main() { // Part 2: display strings in ImmutableArray. Console.WriteLine("ARRAY LENGTH: {0}", _colors.Length); foreach (string value in _colors) { Console.WriteLine(value); } // Part 3: loop over ImmutableList. Console.WriteLine("LIST COUNT: {0}", _sizes.Count); foreach (int value in _sizes) { Console.WriteLine(value); } // Part 4: loop over ImmutableDictionary. Console.WriteLine("DICTIONARY COUNT: {0}", _items.Count); foreach (var pair in _items) { Console.WriteLine(pair); } // Part 5: call Add on ImmutableList, creating a new immutable collection copy. var sizesPlusOne = _sizes.Add(700); Console.WriteLine("LIST COUNT: {0}", _sizes.Count); Console.WriteLine("LIST+1 COUNT: {0}", sizesPlusOne.Count); foreach (int value in sizesPlusOne) { Console.WriteLine(value); } } }ARRAY LENGTH: 3 blue aqua cerulean LIST COUNT: 4 10 20 15 0 DICTIONARY COUNT: 3 [monitor, True] [desk, False] [computer, True] LIST COUNT: 4 LIST+1 COUNT: 5 10 20 15 0 700
The benefit of collections like ImmutableList
is compiler-checking: the compiler enforces that no elements can be changed. Code can act with less concern for unexpected data changes.