08/05/2023
.NET 8 (Preview 1) introduces new collection types including FrozenDictionary
and FrozenSet
. Both types are frozen counterparts of Dictionary<TKey, TValue>
and HashSet<T>
. These types reside in the System.Collections.Frozen
namespace in SystemCollections.Immutable.dll package.
The frozen semantics mean, that these collections resist to change once they become frozen: they are immutable. However, they are different to the existing immutable collections, as these are being even more restrictive to change. While immutable collections allow change by creating a new immutable collection frozen semantics discourage such operations. Immutable collections use 'clever' data structures in memory that make operations like Add
and Remove
(relatively) cheap given the underlying data may not change. Contrary, frozen collections can optimize for lookups (or for construction, but more on that later).
For example, ImmutableStack<T>
uses a linked list implementation instead of using an array as backing data structure. It has two fields: a head which contains data stored by a user, and a tail which is a pointer to the next item on the stack. Pushing a new item to the stack creates a new instance of ImmutableStack<T>
where the head field stores the new data pushed, and the tail references the previous instance of ImmutableStack<T>
.
Note, that these are the actual field names in the implementation of ImmutableStack at the time of writing this blog post.
Find out more