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

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

    Returning an interface type is more general, so (lacking further information on your specific use case) I'd lean towards that. If you want to expose indexing support, choose IList, otherwise ICollection will suffice. Finally, if you want to indicate that the returned types are read only, choose IEnumerable.

    And, in case you haven't read it before, Brad Abrams and Krzysztof Cwalina wrote a great book titled "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" (you can download a digest from here).

提交回复
热议问题