In this article [Show more]
C# Immutable List Example
In C#, an immutable list is a collection that cannot be modified once created. The ImmutableList<T> class, provided by the System.Collections.Immutable namespace, ensures that any changes made result in a new list while the original remains unchanged. This feature is particularly valuable in multithreaded environments, where data integrity and consistency are crucial.
Why Use Immutable Lists?
- Thread Safety: Immutable lists are inherently thread-safe because their data cannot be modified once created.
- Predictable State: Functions using immutable lists are easier to reason about since they don't have side effects.
- Functional Programming: Aligns with functional programming principles that favor immutability.
Creating and Using Immutable Lists
Example: Adding and Modifying Items
Here's how you can create, add, and modify items in an immutable list:
using System;
using System.Collections.Immutable;
public class ImmutableListExample
{
public static void Main()
{
// Create an immutable list with initial items
ImmutableList<string> fruits = ImmutableList.Create("Apple", "Banana", "Cherry");
// Add a new item to the list, returns a new list
ImmutableList<string> updatedFruits = fruits.Add("Date");
// Remove an item from the list, returns a new list
ImmutableList<string> modifiedFruits = updatedFruits.Remove("Banana");
// Display original and updated lists
Console.WriteLine("Original List:");
foreach (var fruit in fruits)
{
Console.WriteLine(fruit);
}
Console.WriteLine("\nUpdated List (Added 'Date'):");
foreach (var fruit in updatedFruits)
{
Console.WriteLine(fruit);
}
Console.WriteLine("\nModified List (Removed 'Banana'):");
foreach (var fruit in modifiedFruits)
{
Console.WriteLine(fruit);
}
}
}
Other Common Operations
- Contains: Checks if a specific item is present in the list.
- IndexOf: Finds the index of an item in the list.
- AddRange: Adds multiple items at once, returning a new list.
- Insert: Inserts an item at a specific index, returning a new list.
Best Practices
- Avoid Excess Copies: Be mindful of creating too many intermediate copies when chaining multiple operations.
- Thread Safety: Take full advantage of the inherent thread safety of immutable lists in multithreaded applications.
- Read-Only List: Consider using a read-only collection if you only need read operations and don't require immutability.
Conclusion
Using ImmutableList<T> in C# provides significant benefits in thread safety and predictability. By understanding how to work with immutable lists and their best practices, you can design more reliable and efficient applications.