Is returning IList worse than returning T[] or List?

前端 未结 5 2146
心在旅途
心在旅途 2020-12-12 12:38

The answers to questions like this: List or IList always seem to agree that returning an interface is better than returning a concrete implementation of a

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 13:45

    No, because the consumer should know what exactly IList is:

    IList is a descendant of the ICollection interface and is the base interface of all non-generic lists. IList implementations fall into three categories: read-only, fixed-size, and variable-size. A read-only IList cannot be modified. A fixed-size IList does not allow the addition or removal of elements, but it allows the modification of existing elements. A variable-size IList allows the addition, removal, and modification of elements.

    You can check for IList.IsFixedSize and IList.IsReadOnly and do what you want with it.

    I think IList is an example of a fat interface and it should have been split into multiple smaller interfaces and it also violates Liskov substitution principle when you return an array as an IList.

    Read more if you want to make decision about returning interface


    UPDATE

    Digging more and I found that IList does not implement IList and IsReadOnly is accessible through base interface ICollection but there is no IsFixedSize for IList. Read more about why generic IList<> does not inherit non-generic IList?

提交回复
热议问题