HimBromBeere HimBromBeere - 1 year ago 62
C# Question

Is IList really a better alternative to an array

Today I read a post from Eric Lipert that describes the harm of arrays. It´s mentioned that when we need a collection of values we should provide values, not a variable that points to a list of values. Thus Eric suggests that whenever we want to return a collection of items in a method, we should return an

, which provides the same as an array, namely it:

  1. enables indexed access

  2. enables iterating the items

  3. is strongly typed

However in contrast to an array the list also provides members that add or remove items and thus modify the collection-object. We could of course wrap the collection into a
and return an
but then we´d lose the indexed accessability. Moreover a caller can´t know if the ReSharper-warning "possible iterations of the same enumerations" applies as he doesn´t know that internally that enumeration is just a list wrapped within a
. So a caller can´t know if the collection was already materialized or not.

So what I want is a collection of items where the collection itself is immutable (the items however don´t have to be, they won´t on an
neither), meaning we can´t add/remove/insert items to the underlying list. However it seems weird to me returning a
from my API, at least I´ve never seen an API doing so.

Thus array seems perfect for my needs, doesn´t it?

hvd hvd
Answer Source

We could of course wrap the collection into a ReadOnlyCollection and return an IEnumerable<T>

Why do that? ReadOnlyCollection<T> implements IList<T>, so unless there's some better approach, declaring a return type of IList<T> and returning an instance of ReadOnlyCollection<T> seems like a good way to go.

However, it just so happens that in current .NET Framework versions, there is a slightly better way: return an instance of ReadOnlyCollection<T>, but specify a return type of IReadOnlyList<T>. While IList<T> doesn't really promise to allow modification by the caller, IReadOnlyList<T> is explicit about the intent.