Should I always return IEnumerable instead of IList?

后端 未结 14 1937
一生所求
一生所求 2020-11-27 11:47

When I\'m writing my DAL or other code that returns a set of items, should I always make my return statement:

public IEnumerable GetRecentItems         


        
相关标签:
14条回答
  • 2020-11-27 12:47

    In general, you should require the most generic and return the most specific thing that you can. So if you have a method that takes a parameter, and you only really need what's available in IEnumerable, then that should be your parameter type. If your method could return either an IList or an IEnumerable, prefer returning IList. This ensures that it is usable by the widest range of consumers.

    Be loose in what you require, and explicit in what you provide.

    0 讨论(0)
  • 2020-11-27 12:48

    TL; DR; – summary

    • If you develop in-house software, do use the specific type(Like List) for the return values and the most generic type for input parameters even in case of collections.
    • If a method is a part of a redistributable library’s public API, use interfaces instead of concrete collection types to introduce both return values and input parameters.
    • If a method returns a read-only collection, show that by using IReadOnlyList or IReadOnlyCollection as the return value type.

    More

    0 讨论(0)
提交回复
热议问题