In this article [Show more]
C# Immutable Dictionary
In C#, an ImmutableDictionary<TKey, TValue> is a thread-safe, read-only collection that stores key-value pairs. Once created, its content cannot be modified directly. Instead, any "modification" operation, such as adding or removing an element, returns a new instance, leaving the original collection unchanged. This makes it a valuable tool for applications requiring data integrity and thread safety.
Key Benefits of ImmutableDictionary
- Thread Safety: Immutable collections prevent race conditions because they cannot be altered once created.
- Predictable State: Any function or method using immutable dictionaries has predictable results, as the collection's state is consistent.
- Efficient Changes: Returns new dictionaries with changes applied, sharing unchanged data efficiently.
Creating and Using ImmutableDictionary
Example: Adding and Modifying Key-Value Pairs
Here's how to create and modify an immutable dictionary in C#:
using System;
using System.Collections.Immutable;
public class ImmutableDictionaryExample
{
public static void Main()
{
// Create an immutable dictionary
var capitals = ImmutableDictionary<string, string>.Empty
.Add("USA", "Washington, D.C.")
.Add("UK", "London")
.Add("France", "Paris");
// Add a new key-value pair, returns a new dictionary
var updatedCapitals = capitals.Add("Germany", "Berlin");
// Modify an existing value, returns a new dictionary
var modifiedCapitals = updatedCapitals.SetItem("UK", "Edinburgh");
Console.WriteLine("Original Dictionary:");
foreach (var entry in capitals)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
Console.WriteLine("\nUpdated Dictionary (Added Germany):");
foreach (var entry in updatedCapitals)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
Console.WriteLine("\nModified Dictionary (Changed UK):");
foreach (var entry in modifiedCapitals)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
}
}
Other Common Operations
- Remove: Removes a key-value pair, returning a new dictionary.
- TryGetValue: Attempts to retrieve a value without exceptions.
- ContainsKey: Checks if a key exists in the dictionary.
- SetItems: Adds or updates multiple key-value pairs at once.
Best Practices for ImmutableDictionary
- Avoid Frequent Copies: Minimize intermediate copies when chaining multiple operations to reduce overhead.
- Thread Safety: Take advantage of the inherent thread safety for concurrent data access.
- Capacity Management: Use the builder pattern to efficiently add or modify multiple items.
Conclusion
The ImmutableDictionary<TKey, TValue> in C# is a valuable collection for applications requiring predictable state and thread safety. By understanding how to use its methods effectively, you can build efficient and reliable collections that are easy to manage.