List of Immutable Collections in C# with Example
In C#, immutable collections are designed to provide a way to manage collections that cannot be modified after their creation. This feature is essential for developing applications that require thread safety, predictability, and clear intent. The System.Collections.Immutable namespace in the .NET Library provides several immutable collection types. This article explores these immutable collections and provides examples of their usage.
Immutable Collections Overview
Immutable collections in C# ensure that the collection's state cannot be altered once it is created. Instead of modifying an existing collection, any "modification" operation such as adding or removing items returns a new collection with the desired changes, leaving the original collection unchanged.
Key Benefits
- Thread Safety: Immutable collections are inherently thread-safe because their data cannot be modified after creation.
- Predictability: Functions that use immutable collections are easier to reason about because they don't have side effects that alter the collection.
- Performance: Efficient in scenarios involving concurrent access from multiple threads.
Common Immutable Collections
1. ImmutableList<T>
Represents an immutable list, which is a list whose contents cannot be changed.
Example Usage
using System;
using System.Collections.Immutable;
public class ImmutableListExample
{
public static void Main()
{
ImmutableList<string> names = ImmutableList.Create("Alice", "Bob", "Charlie");
ImmutableList<string> updatedNames = names.Add("Diana");
Console.WriteLine("Original list:");
foreach (var name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("\nUpdated list:");
foreach (var name in updatedNames)
{
Console.WriteLine(name);
}
}
}
2. ImmutableArray<T>
Provides an immutable version of an array.
Example Usage
using System;
using System.Collections.Immutable;
public class ImmutableArrayExample
{
public static void Main()
{
ImmutableArray<int> numbers = ImmutableArray.Create(1, 2, 3);
ImmutableArray<int> updatedNumbers = numbers.Add(4);
Console.WriteLine("Original array:");
foreach (var number in numbers)
{
Console.WriteLine(number);
}
Console.WriteLine("\nUpdated array:");
foreach (var number in updatedNumbers)
{
Console.WriteLine(number);
}
}
}
3. ImmutableDictionary<TKey, TValue>
An immutable version of a dictionary.
Example Usage
using System;
using System.Collections.Immutable;
public class ImmutableDictionaryExample
{
public static void Main()
{
ImmutableDictionary<string, string> capitals = ImmutableDictionary.CreateBuilder<string, string>()
.Add("USA", "Washington, D.C.")
.Add("Canada", "Ottawa")
.ToImmutable();
// Attempting to add more elements will result in a new dictionary
ImmutableDictionary<string, string> updatedCapitals = capitals.Add("Germany", "Berlin");
Console.WriteLine("Original dictionary:");
foreach (var capital in capitals)
{
Console.WriteLine($"{capital.Key}: {capital.Value}");
}
Console.WriteLine("\nUpdated dictionary:");
foreach (var capital in updatedCapitals)
{
Console.WriteLine($"{capital.Key}: {capital.Value}");
}
}
}
4. ImmutableHashSet<T>
An immutable version of a hash set.
Example Usage
using System;
using System.Collections.Immutable;
public class ImmutableHashSetExample
{
public static void Main()
{
ImmutableHashSet<string> fruits = ImmutableHashSet.Create("Apple", "Banana", "Cherry");
ImmutableHashSet<string> updatedFruits = fruits.Add("Date");
Console.WriteLine("Original set:");
foreach (var fruit in fruits)
{
Console.WriteLine(fruit);
}
Console.WriteLine("\nUpdated set:");
foreach (var fruit in updatedFruits)
{
Console.WriteLine(fruit);
}
}
}
Conclusion
Immutable collections in C# provide significant advantages in scenarios requiring data integrity, concurrent access, and thread safety. By understanding how to use these collections, developers can design more robust and predictable applications.