21.6 C
New York
Friday, June 13, 2025

How to use frozen collections in C#



  • FrozenDictionary<TKey,TValue>: A FrozenDictionary represents a read-only dictionary that is optimized for fast searches. You can use this collection when the collection needs to be created once and read frequently.
  • FrozenSet<T>: A FrozenSet represents a read-only immutable set optimized for fast searches and enumeration. Like a FrozenDictionary, you cannot alter this collection after creation.

Because both FrozenSet and FrozenDictionary are read-only collections, you cannot add, change, or remove items in these collections.

Create frozen collections in C#

The following code snippet shows how you can create a FrozenSet from a HashSet instance, populate it with sample data, and then search for an item inside it. Recall that a HashSet is an unordered collection of unique elements that supports set operations (union, intersection, etc.) and uses a hash table for storage.


var hashSet = new HashSet { "A", "B", "C", "D", "E" };
var frozenSet = hashSet.ToFrozenSet();
bool isFound = frozenSet.TryGetValue("A", out _);

In the preceding code snippet, the ToFrozenSet() method is used to convert a HashSet instance to a FrozenSet instance. The method TryGetValue() will return true in this example because the data searched for is present in the collection.

The following code shows how you can create a FrozenDictionary, store data in it, and search for a particular key in the collection.


var dictionary = new Dictionary
{
    { 1, "A" },{ 2, "B" },{ 3, "C" },{ 4, "D" },{ 5, "E" }
};
var frozenDictionary = dictionary.ToFrozenDictionary();
bool isFound = dictionary.TryGetValue(7, out _);

When the above code is executed, the TryGetValue method will return false because the key 7 is not available in the collection.

Benchmarking performance of frozen collections in .NET Core

Let us now benchmark the performance of a frozen collection, specifically a FrozenSet, against other collection types using the BenchmarkDotNet library. For comparison, we’ll use a List, a HashSet, and an ImmutableHashSet.

Recall that a List is a mutable, strongly-typed, dynamically-sized, ordered collection of elements (even duplicates), and that a HashSet is a mutable, array-based collection of unique elements that is optimized for fast look-ups. Note that the time complexity for searching an item in a HashSet is O(1), compared to a time complexity of O(n) for a List (where n is the number of elements in the collection). Clearly, a HashSet is useful in cases where quick access is necessary. On the downside, a HashSet consumes more memory than a List and cannot include duplicate elements. You should use a List if you want to store an ordered collection of items (possibly duplicates) and where resource consumption is a constraint.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles