ReadOnly Collections vs Immutable Collections
Amir Doosti
Software Engineer | 20+ Years of Expertise | .NET, Industrial Automation with Beckhoff, Microservices Architecture
In C#, both readonly collections and immutable collections aim to prevent modifications to the collection, but they differ in how they accomplish this and in the guarantees they provide.
In this article I want to have a deep look into their differences as well as other related topics.
Readonly Collections
A readonly collection is a wrapper or proxy around an existing collection that prevents modifications through the collection interface, but the underlying collection can still be modified indirectly if other references to it exist.
Namespace: System.Collections.ObjectModel
Example: ReadOnlyCollection<T>
Important points:
List<int> list = new List<int> { 1, 2, 3 };
ReadOnlyCollection<int> readOnlyList = new ReadOnlyCollection<int>(list);
// Cannot modify via readOnlyList
// readOnlyList.Add(4); // Error: ReadOnlyCollection does not allow modification
// Can modify the original list
list.Add(4);
// readOnlyList will reflect changes from the original list
Console.WriteLine(readOnlyList.Count); // Output: 4
ReadOnly Collection Classes
The System.Collections.ObjectModel workspace contains several other read only classes like:
As the fundamentals are more or less the same, so I focus on ReadOnlyCollection.
You saw in the previous example that by passing a collection to the constructor of ReadOnlyCollection, we can create a read only wrapper of it.
Another way is using the AsReadOnly() method for most collections:
List<string> names=new List<string>(){"Rod", "Jane", "Freddy"};
Then you can convert like this:
ReadOnlyCollection<string> readOnlyNames=names.AsReadOnly();
Immutable Collections
An immutable collection is a collection that guarantees that it cannot be modified in any way, once created. Immutable collections do not allow any modifications at all, even if other references to the collection exist.
Namespace: System.Collections.Immutable
Example: ImmutableList<T>, ImmutableArray<T>
Important points:
Example:
using System.Collections.Immutable;
ImmutableList<int> immutableList = ImmutableList.Create(1, 2, 3);
// Modifying operations return a new collection
ImmutableList<int> newList = immutableList.Add(4);
// The original collection remains unchanged
Console.WriteLine(immutableList.Count); // Output: 3
Console.WriteLine(newList.Count); // Output: 4
Immutable Collection Classes
This namespace contains lots of collection classes including both generics and non-generics:
Differences Summary
In the following table I summerised the key differences between ReadOnly and Immutable collections:
Time complexity
When comparing performance between a normal List<T>, a readonly list (ReadOnlyCollection<T>), and an immutable list (ImmutableList<T>), there are some key performance characteristics to consider. Each collection type is designed for specific use cases, and their performance profiles vary depending on the operations you're performing.
Normal List (Listlt;Tgt;) Operations
Example:
领英推荐
List<int> list = new List<int> { 1, 2, 3 };
list.Add(4); // Fast addition
list[1] = 10; // Direct modification
ReadOnly List (ReadOnlyCollectionlt;Tgt;) Operations
Example:
List<int> list = new List<int> { 1, 2, 3 };
ReadOnlyCollection<int> readOnlyList = new ReadOnlyCollection<int>(list);
// Access is fast but no modification is allowed via readOnlyList
Immutable List (ImmutableListlt;Tgt;) Operations
Example:
ImmutableList<int> immutableList = ImmutableList.Create(1, 2, 3);
ImmutableList<int> newList = immutableList.Add(4); // Returns a new list with 4
Performance Comparison
Read and Access Time
Modification
Memory Overhead
Performance Summary Table
In this table I summarised performance comparison between normal list and ReadOnly and Immutable list:
How about using the readonly keyword?
The readonly keyword in C# and the ReadOnlyCollection<T> class both limit modifications to collections, but they work in different ways and have different implications. Let's explore the differences, pros, and cons of using readonly with a collection vs. using ReadOnlyCollection<T>.
readonly Keyword
The readonly keyword in C# is used to ensure that a field (like a collection) can only be assigned a value during its initialization (in the constructor or at the point of declaration). However, it does not prevent modifications to the elements within the collection while the two other collections ReadOnly and Immutable protect the collection from modification. Note to this example:
class Test
{
public readonly List<int> myList = new List<int> { 1, 2, 3 };
public void AddItem()
{
myList.Add(4); // Allowed
}
public void ReplaceList()
{
// myList = new List<int>(); // Not allowed (compile-time error)
}
}
Pros:
Cons:
Usage:
The following table may help you to have better understanding about differences between using readonly keyword and ReadOnlyCollection:
Conclusion
Choosing between these depends on your specific use case:
#csharp #dotnet #collections #readonly #immutable #readonlycollection