Why does C# `List` implements `IReadOnlyCollection`?

33 views Asked by At

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.

0

There are 0 answers