Why List<T>
implements IReadOnlyList<T>
even though List<T>
is not read only?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With