Returning 'IList' vs 'ICollection' vs 'Collection'

后端 未结 6 1733
萌比男神i
萌比男神i 2020-11-28 20:17

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,

6条回答
  •  离开以前
    2020-11-28 20:36

    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 : ICollection, 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.

提交回复
热议问题