C# – Should I always return IEnumerable instead of IList


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()


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.

Best Solution

Framework design guidelines recommend using the class Collection when you need to return a collection that is modifiable by the caller or ReadOnlyCollection for read only collections.

The reason this is preferred to a simple IList is that IList does not inform the caller if its read only or not.

If you return an IEnumerable<T> instead, certain operations may be a little trickier for the caller to perform. Also you no longer will give the caller the flexibility to modify the collection, something that you may or may not want.

Keep in mind that LINQ contains a few tricks up its sleeve and will optimize certain calls based on the type they are performed on. So, for example, if you perform a Count and the underlying collection is a List it will NOT walk through all the elements.

Personally, for an ORM I would probably stick with Collection<T> as my return value.