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

后端 未结 6 1737
萌比男神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:29

    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:

    1. It disallows changes to the collection (but not to the elements, if they are of reference type).

    2. 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.Add(item) 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.

提交回复
热议问题