I am confused about which collection type that I should return from my public API methods and properties.
The collections that I have in mind are IList
,
The main difference between IList
and ICollection
is that IList
allows you to access elements via an index. IList
describes array-like types. Elements in an ICollection
can only be accessed through enumeration. Both allow the insertion and deletion of elements.
If you only need to enumerate a collection, then IEnumerable
is to be preferred. It has two advantages over the others:
It disallows changes to the collection (but not to the elements, if they are of reference type).
It allows the largest possible variety of sources, including enumerations that are generated algorithmically and are not collections at all.
Collection
is a base class that is mainly useful to implementers of collections. If you expose it in interfaces (APIs), many useful collections not deriving from it will be excluded.
One disadvantage of IList
is that arrays implement it but do not allow you to add or remove items (i.e. you cannot change the array length). An exception will be thrown if you call IList
on an array. The situation is somewhat defused as IList
has a Boolean property IsReadOnly
that you can check before attempting to do so. But in my eyes, this is still a design flaw in the library. Therefore, I use List
directly, when the possibility to add or remove items is required.