Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does List<T> implement IReadOnlyList<T> in .NET 4.5?

Why does List<T> implement IReadOnlyList<T> in .NET 4.5?

List<T> isn't read only...

like image 228
James Newton-King Avatar asked Mar 07 '13 04:03

James Newton-King


People also ask

What is IReadOnlyCollection in c#?

The IReadOnlyCollection interface extends the IEnumerable interface and represents a basic read-only collection interface. It also includes a Count property apart from the IEnumerable members as shown in the code snippet given below.


2 Answers

Because List<T> implements all of the necessary methods/properties/etc. (and then some) of IReadOnlyList<T>. An interface is a contract that says "I can do at least these things."

The documentation for IReadOnlyList<T> says it represents a read-only collection of elements.

That's right. There are no mutator methods in that interface. That's what read-only means, right? IReadOnlyList<T> is used in the "typical" (contract) way, not as a marker.

like image 113
Matt Ball Avatar answered Oct 09 '22 07:10

Matt Ball


Interfaces only describes functionality which will be implemented. It does not describe functionality which will not be implemented. IReadOnlyList is therefore an incorrect interface name, as it cannot dictate that write functionality will not be written.

The methods/functions of describe that you can read the contents of the list. The interface should have been IReadableList instead of IReadOnlyList.

like image 41
Rbrt Avatar answered Oct 09 '22 08:10

Rbrt