Using FrozenDictionary for read-only lookup data in .NET

Posted: (EET/GMT+2)

 

If you have lookup data in .NET that never changes at runtime, the FrozenDictionary class is worth checking out. It is one of those classes that are genuinely useful in production.

The FrozenDictionary<TKey, TValue> was introduced in .NET 8 (and .NET Framework 4.6.2) to optimize dictionaries that are built once and then only read. After creation, the data is immutable, allowing the runtime to use a more compact and faster internal layout.

A common example is reference data loaded from a database at startup, such as IDs mapped to names. For instance, along these lines:

using System.Collections.Frozen;

var rows = LoadLookupRowsFromDatabase();
var lookup = rows.ToFrozenDictionary(r => r.Id, r => r.Name);

Once created, the dictionary cannot be modified. Reads are fast, memory usage is lower than a regular Dictionary, and the intent is clear: this data is static.

You might also ask, how fast is the reading compared to a normal dictionary? Microsoft's tests indicate read speed is around 50% faster, which is a great amount, but you have to put it in context: a regular dictionary is very fast already.

Even so, a FrozenDictionary works well for:

  • Lookup tables (status codes, types, regions)
  • Configuration data loaded at startup
  • Reference data cached from SQL that rarely or never changes.

If the underlying data changes, rebuild the FrozenDictionary instead of mutating it. That keeps access predictable and avoids accidental writes.

Tip: if your code never calls Add, Remove, or index assignment on a regular dictionary, a frozen collection is often a better fit.