KingNestor KingNestor - 2 months ago 11
C# Question

Should I always return IEnumerable<T> instead of IList<T>?

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

public IEnumerable<FooBar> GetRecentItems()


or

public IList<FooBar> GetRecentItems()


Currently, in my code I have been trying to use IEnumerable as much as possible but I'm not sure if this is best practice? It seemed right because I was returning the most generic datatype while still being descriptive of what it does, but perhaps this isn't correct to do.

Answer

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

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

  • 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<T>.

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