In .NET 8.0, the FrozenDictionary class provides a fast, unchangeable collection ideal for read-only scenarios. This blog will explain what it is, how it differs from other dictionaries, and how to use it in your applications.
What is FrozenDictionary?
FrozenDictionary is part of the System.Collections.Frozen namespace introduced in .NET 8.0. It is a dictionary that cannot be changed after it is created. Once a FrozenDictionary is initialized, its contents cannot be modified—no items can be added, removed, or altered.
Key Features of FrozenDictionary
- Immutability: The contents are fixed once created, ensuring thread safety and removing the need for locks during data access.
- Performance: Optimized for fast read operations, ideal for scenarios with frequent reads and no modifications.
- Memory Efficiency: Uses minimal memory while maintaining quick access times, beneficial for memory-limited environments or high-performance applications.
- Thread Safety: Its immutable nature makes it inherently safe for concurrent read operations.
Creating and Using FrozenDictionary
Here’s how you can create and use a FrozenDictionary in your .NET 8.0 application.
The source code is available in GitHub.
Example Hard-Coding Data
In this example, we create a FrozenDictionary with hard-coded values and use it to validate input codes.
using System.Collections.Frozen;
namespace FrozenDictionaryExample
{
public class CategoryDictionary
{
public FrozenDictionary<string, string> Categories { get; }
public CategoryDictionary()
{
// Initialize the FrozenDictionary with hard-coded values
var dictionary = new Dictionary<string, string>
{
{ "A123", "Category1" },
{ "B456", "Category2" },
{ "C789", "Category3" }
};
Categories = dictionary.ToFrozenDictionary();
}
public string GetCategory(string code)
{
// Fast access to values
return Categories.TryGetValue(code, out var category) ? category : "Unknown Category";
}
}
}
// Web API
using FrozenDictionaryExample;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapGet("/category/{category}", ([FromRoute] string category) =>
{
var categoryDictionary = new CategoryDictionary();
return Results.Ok(categoryDictionary.GetCategory(category));
})
.WithName("GetCategory")
.WithOpenApi();
app.Run();
Explanation
- Initialization: In the CategoryDictionary constructor, we create a regular Dictionary<string, string> and convert it to a FrozenDictionary using the ToFrozenDictionary() extension method.
- Access: The GetCategory method demonstrates how to efficiently access values from the FrozenDictionary.
When to Use FrozenDictionary?
- Read-Only Scenarios: Ideal when the data is static and only needs to be accessed, not modified. Examples include configuration settings, lookup tables, and constant mappings.
- Performance-Critical Applications: Useful in high-performance scenarios where fast, immutable data access is required.
Benefits
- Fast Lookups: Optimized for quick access to data.
- Thread Safety: No need for synchronization during read operations.
- Memory Efficiency: Designed to be memory efficient.
Limitations
No Modifications: The dictionary cannot be updated after creation. Any changes require creating a new instance.
Conclusion
FrozenDictionary in .NET 8.0 provides an efficient, immutable solution for scenarios requiring high-performance read operations. By leveraging its immutability and optimization features, you can ensure fast, thread-safe access to your data while simplifying your codebase. Whether you’re dealing with static configuration data or need a reliable, read-only data structure, FrozenDictionary is a powerful tool to include in your .NET 8.0 applications.