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
,
IList
is the base interface for all generic lists. Since it is an ordered collection, the implementation can decide on the ordering, ranging from sorted order to insertion order. Moreover Ilist
has Item property that allows methods to read and edit entries in the list based on their index.
This makes it possible to insert, remove a value into/from the list at a position index.
Also since IList
, all the methods from ICollection
are also available here for implementation.
ICollection
is the base interface for all generic collections. It defines size, enumerators and synchronization methods. You can add or remove an item into a collection but you cannot choose at which position it happens due to the absence of index property.
Collection
provides an implementation for IList
, IList
and IReadOnlyList
.
If you use a narrower interface type such as ICollection
instead of IList
, you protect your code against breaking changes. If you use a wider interface type such as IList
, you are more in danger of breaking code changes.
Quoting from a source,
ICollection
,ICollection
: You want to modify the collection or you care about its size.IList
,IList
: You want to modify the collection and you care about the ordering and / or positioning of the elements in the collection.