How to Create Immutable List in C#
In C#, an ImmutableList<T> is a collection that cannot be modified once it is created. It belongs to the System.Collections.Immutable namespace and provides benefits like thread safety and predictable state, especially in scenarios where data integrity is crucial. This article explains how to create an ImmutableList<T>, how to add elements to it, and best practices for managing such lists.
Creating an Immutable List
Using ImmutableList.Create
The simplest way to create an ImmutableList<T> is by using the Create method. This method can accept a set of initial values or be called without parameters to create an empty list.
using System;
using System.Collections.Immutable;
public class ImmutableListCreateExample
{
public static void Main()
{
// Create an immutable list with initial elements
ImmutableList<string> fruits = ImmutableList.Create("Apple", "Banana", "Cherry");
// Print the elements of the immutable list
Console.WriteLine("Immutable List of Fruits:");
foreach (var fruit in fruits)
{
Console.WriteLine(fruit);
}
// Create an empty immutable list
ImmutableList<int> emptyNumbers = ImmutableList<int>.Empty;
Console.WriteLine("\nEmpty Immutable List:");
Console.WriteLine($"Count: {emptyNumbers.Count}");
}
}
Adding and Modifying Elements
Adding or modifying elements in an ImmutableList<T> returns a new list, while the original remains unchanged. Here’s how you can use the Add, AddRange, Remove, and SetItem methods:
using System;
using System.Collections.Immutable;
public class ImmutableListAddModifyExample
{
public static void Main()
{
// Create an empty immutable list
ImmutableList<int> numbers = ImmutableList<int>.Empty;
// Add elements to the immutable list
ImmutableList<int> updatedNumbers = numbers.Add(1).Add(2).Add(3);
// Add multiple elements using AddRange
updatedNumbers = updatedNumbers.AddRange(new[] { 4, 5 });
// Modify an existing element using SetItem
updatedNumbers = updatedNumbers.SetItem(0, 10);
// Remove an element
updatedNumbers = updatedNumbers.Remove(3);
// Display the final immutable list
Console.WriteLine("Final Immutable List of Numbers:");
foreach (var number in updatedNumbers)
{
Console.WriteLine(number);
}
}
}
Best Practices for Using ImmutableList
- Minimize Copies: Be cautious about chaining too many operations together, as it may result in unnecessary intermediate copies.
- Thread Safety: Take advantage of the inherent thread safety of immutable lists for concurrent access.
- Predictable State: Use ImmutableList<T> when predictable state is important and data changes should be explicit.
Conclusion
Creating an ImmutableList<T> in C# is straightforward using the Create method and subsequent modification methods like Add, Remove, and SetItem. With the proper application of immutable lists, your C# applications can achieve greater data integrity, predictability, and thread safety.