0

By looking at the documentation, between .NET Framework v4.0 and v4.5 the List<T> started implementing the IReadOnlyCollection<T> interface. The documentation of IReadOnlyCollection<T> says:

Represents a strongly-typed, read-only collection of elements.

I am confused on why List implements such an interface. After all, can't the list items be modified? I think I am likely misinterpreting the meaning of "read-only collection" in this context, but I do not understand how. For example, as the MSDN documentation states for the ReadOnlyCollection<T> class:

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.

The ReadOnlyCollection<T> class in fact does not allow, for instance, to Add elements.

Furthermore, in later versions of .NET, some types have been introduced which are explicitly for immutable lists:

  • IImmutableList<T> interface although introduced much later, in .NET 6.
  • For the class ImmutableList<T>, the documentation says: When you add or remove items from an immutable list, a copy of the original list is made with the items added or removed, and the original list is unchanged.
  • The ImmutableArray<T> struct is another example.

Any clarification is appreciated.

alelom
  • 2,130
  • 3
  • 26
  • 38
  • 2
    Does this answer your question? [Why does List implement IReadOnlyList in .NET 4.5?](https://stackoverflow.com/questions/15262981/why-does-listt-implement-ireadonlylistt-in-net-4-5) (found by googling the **title** of your question) – Franz Gleichmann Oct 26 '22 at 18:04
  • Google is better for searching existing StackOverflow posts than StackOverflow search! I thought the opposite would be true... :( – alelom Oct 26 '22 at 19:46
  • [This](https://user-images.githubusercontent.com/6352844/198123250-b716cb75-cd12-4c3e-86ca-d46df34de74d.png) is what can be seen by searchig with SO. Before posting and wasting time writing the question, I also searched with SO search other combinations of the terms. This is really disappointing. Next time I will use Google to search for duplicates instead. – alelom Oct 26 '22 at 19:53

0 Answers0