Search code examples
c#.netimmutable-collections

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.


Solution

  • 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.