List<T>.AsReadOnly() vs IReadOnlyCollection<T>

Solution 1:

If you just return an actual List<T> as an IReadOnlyList<T>, then the caller can always just cast it back, and then modify the list as they please. Conversely, calling AsReadOnly() creates a read-only wrapper of the list, which consumers can't update.

Note that the read-only wrapper will reflect changes made to the underlying list, so code with access to the original list can still update it with the knowledge that any consumers of the read-only version will see those changes.

Solution 2:

First of all it's not that AsReadOnly() was added because IReadOnlyList<T> isn't good enough -- IReadOnlyList<T> is only available starting with .NET 4.5 while AsReadOnly() method exists since .NET 2.

More importantly: AsReadOnly() and IReadOnlyList<T> serve very different purposes.

ReadOnlyCollection<T> is meant for implementing object models, for example things like Dictionary<K,V>.Keys and Dictionary<K,V>.Values. This is for scenarios where consumers shouldn't be able to change the contents while the producer can. It works in tandem with Collection<T> which provides hooks for the owner to validate changes or perform side effects when items get added.

IReadOnlyList<T> on the other hand is simply an interface that provides a read-only view of the collection. Methods can use it in order to say "I need a random access collection but I don't need to be able to modify it". For example, a BinarySearch method might look like this:

public int BinarySearch<T>(IReadOnlyList<T> list, int start, int length);

In order to make this method useful, it's required to be able to pass in any List. Forcing to create wrapper collections would be prohibitively expensive.