Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does List<T> implement IReadOnlyList<T> interface? [duplicate]

Tags:

c#

.net

Why List<T> implements IReadOnlyList<T> even though List<T> is not read only?

like image 591
Doug Avatar asked Feb 10 '14 19:02

Doug


2 Answers

It allows you to expose a read only "proxy" of that list, so that you can pass that interface reference elsewhere and know that the code won't mutate the list. (Technically it can try to cast it back to something like List and mutate it, but it shouldn't do that.)

It also allows a method to specifically indicate that while it needs to accept a list, it won't mutate it.

Having a read-only interface also allows that interface to be covariant, unlike List or IList.

like image 54
Servy Avatar answered Sep 30 '22 17:09

Servy


You can think of this in terms of subtyping. A regular list can be a readonly list if you don't modify it, ie List<T> is a subtype of IReadOnlyList<T> (I'm not sure if the C# types actually bear that out). The typing allows you to specify that a particular piece of code won't make any changes to the list.

Another example of this kind of thing is in C where you can pass an int to a method that accepts a const int or a pass an int to a method that expects a volatile int. Treating the argument more stringently than is needed isn't harmful.

like image 45
mrmcgreg Avatar answered Sep 30 '22 18:09

mrmcgreg