Colonel Panic
Colonel Panic

Reputation: 137584

Why use ImmutableList over ReadOnlyCollection?

.NET 4.5 has a new namespace System.Collections.Immutable

This package provides collections that are thread safe and guaranteed to never change their contents, also known as immutable collections.

I'm confused. Isn't the thread safety problem already solved by the ReadOnlyCollection class? Why use ImmutableList instead?


I know there's also an IReadOnlyList interface. That doesn't solve the thread safety problem implicitly, because other threads may edit the object by another interface.

Upvotes: 119

Views: 50846

Answers (6)

erhan355
erhan355

Reputation: 1086

So far all technical aspects was told but no code. I created a small example shows main difference.

Consider both readonly collection and immutable list pointing same object in this case "strings list".

If we add a new item to "strings list" after readonly collection creation , we can see that readonly collection is modified.(So we managed to find a way to mutate readonly collection)

However,when we take same steps on immutable lists,immutable list stays intact

List<string> strings = new List<string>()
{
    "Visual Studio 2017","Visual Studio 2019"
};
ReadOnlyCollection<string> readOnlyStrings = strings.AsReadOnly();
var immutableList = strings.ToImmutableList();
strings.Add("Visual Studio 2022");
Console.WriteLine("Readonly List");

foreach (string item in readOnlyStrings)
{
    Console.WriteLine(item);
}
Console.WriteLine("Immutable List");

foreach (string item in immutableList)
{
    Console.WriteLine(item);
}

Screenshot

Upvotes: 6

andypea
andypea

Reputation: 1401

The main benefit is memory efficiency, not thread-safety.

The immutable collections in System.Collections.Immutable are designed in a way that allows modified versions of the collection to share data structures with un-modified copies of the same collection. The differences are encoded in clever ways that don't require duplication of the whole data structure. There is nice explanation of this at Immutable Collections.

ReadOnlyCollection requires a completely seperate copy of the collection to be created whenever a modification is made. This uses more memory and puts a higher load on the garbage collector.

As you've observed, both classes seek to guarantee that the collection can't have observable modifications. And both classes achieve that to some extent, assuming they aren't misused.

Upvotes: 2

Zoran Horvat
Zoran Horvat

Reputation: 11301

In multi-threaded scenarios, be advised that read-only collections are still not thread-safe.

From the ReadOnlyCollection<T> documentation:

... if changes are made to the underlying collection, the read-only collection reflects those changes

Since collections, like List<T> and others, are not thread safe, so is not the read-only collection.

Important: There are some corner cases which you won't find explicitly explained in MSDN. Some of the operations that seemingly only read content of a collection, are in fact modifying the internal structures of the collection. Why is this not specified? - One obvious reason is because that is an implementation detail which doesn't reflect on the API. The result is that even if you don't modify the List<T> wrapped into an ReadOnlyCollection<T>, and only use getters, the crash could still happen in multi-threaded environment!

Bottom line is that common collections, even when wrapped into a ReadOnlyCollection cannot be used in multi-threaded environment out of the box.

As opposed to ReadOnlyCollection, immutable collections do guarantee that none of the internal structures will ever change after a reference to a collection has been obtained. Note that these structures are still not truly immutable. They are, instead, freezable. That means that the structure will internally change for a while until it is frozen and returned to the caller. Beyond that point, all other calls on the immutable collection will only make modifications outside the structures accessible through the original reference.

Conclusion: Read-only collections are not thread-safe; immutable collections are thread-safe.

Upvotes: 10

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73472

ReadOnlyCollection<T> doesn't solve any of the thread safety problems. It is merely a wrapper around Ilist<T>. It doesn't exposes members to modify the collection, but you can always modify it with the underlying collection reference.

If the underlying collection is modified, it isn't safe to enumerate the ReadOnlyCollection<T>. If you do, you'll get the same InvalidOperationException with message "Collection was modified; enumeration operation may not execute...".

From ReadOnlyCollection<T>

A ReadOnlyCollection can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

ImmutableList on the other hand is immutable and thus inherently thread safe.

Upvotes: 43

dcastro
dcastro

Reputation: 68670

ReadOnlyCollection, as the name suggests, can only be read.

On the other hand, you can append/remove items to/from an ImmutableList by calling its Add/Remove/Clear methods, for example, which return a new immutable list.

Upvotes: 38

James Thorpe
James Thorpe

Reputation: 32202

With a ReadOnlyCollection:

A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.

This can't happen with an ImmutableList.

Upvotes: 114

Related Questions