Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 811
Colonel Panic Avatar asked May 11 '15 10:05

Colonel Panic


People also ask

Why use ImmutableList?

When you don't expect to modify a collection, it's a good practice to defensively copy it into an immutable collection. Immutable lists have many advantages over their mutable siblings, like they are thread-safe, more memory-efficient, and can be passed to untrusted libraries without any side effects.

Is Ireadonlycollection immutable?

3 Answers. Show activity on this post. The fact that ReadOnlyCollection is immutable means that the collection cannot be modified, i.e. no objects can be added or removed from the collection. This does not mean that the objects it contains immutable.

What is immutable list in C#?

Represents an immutable list, which is a strongly typed list of objects that can be accessed by index.

Is immutable list thread safe C#?

List<T> is not thread safe while ConcurrentBag is.


2 Answers

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.

like image 97
James Thorpe Avatar answered Oct 13 '22 05:10

James Thorpe


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.

like image 24
Sriram Sakthivel Avatar answered Oct 13 '22 06:10

Sriram Sakthivel