Should I always return IEnumerable instead of IList?

后端 未结 14 1984
一生所求
一生所求 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:28

    It really depends on why you are using that specific interface.

    For example, IList has several methods that aren't present in IEnumerable:

    • IndexOf(T item)
    • Insert(int index, T item)
    • RemoveAt(int index)

    and Properties:

    • T this[int index] { get; set; }

    If you need these methods in any way, then by all means return IList.

    Also, if the method that consumes your IEnumerable result is expecting an IList, it will save the CLR from considering any conversions required, thus optimizing the compiled code.

提交回复
热议问题