I wish to return an ordered list of items from a method. Should my return type be IEnumerable or IList?
IEnumerable is less specific than an IList, that is, IList has functions that IEnumerable does not.
Compare the two to see if one has functions you need that the other does not.
If you want to return an ordered list maybe you should return a SortedList.
http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.aspx
You can associate an order with the objects.
An IList has the methods for changing the items (like Add), maybe you want to select between ICollection and IEnumerable.
The ICollection extends IEnumerable and has the Count property available that can be useful.
Its easy, if the caller should only use it Readonly, use IEnumerable. as this is then also supports covariance (result can be casted to a base type)
Generally, it's better to return IEnumerable<T>
, as long as that has everything the caller needs.
IEnumerable<T>
is foreachable, which is all that's needed for many consumers. It's also read-only, which is often a good thing -- it means you can sometimes optimize by returning your actual backing collection, without worrying too much about someone modifying it without telling you.
However, if the consumer needs methods that aren't on IEnumerable<T>
, then IList<T>
might make more sense. For example, the caller may want to call Contains
, which isn't on IEnumerable<T>
. Or the caller may want to index into the list, rather than iterating it from start to finish.
But you can do Contains and indexing on IEnumerable<T>
too, via LINQ's Contains and ElementAt extension methods. So there's a question of degree here. If the caller only needs to ask one question that isn't available on IEnumerable<T>
, like "is this empty", then return an IEnumerable<T>
and use the Any extension method. But if the caller uses IList<T>
operations extensively, return IList<T>
.
There is a hierarchy here: interface IList<T> : IEnumerable<T>, ...;
You want to aim for the least possible coupling, so return an IEnumerable<T>
if that is enough. It probably will be.
Return an IList<T>
if the situation requires that the caller gets a List that it can use to Add/Insert/Remove. But even then, it might be better if the caller created his own List from the IEnumerable collection.
It depends what you want to do with the result. If you need to get the count of items or get random access to individual items, go with an IList.
If callers just want to iterate through the items then go with IEnumerable - but you should document whether or not the returned value will be evaluated lazily or not - many IEnumerable instances these days represent queries that will be executed when the collection is enumerated. To be on the safe side, if what you are returning won't be evaluated on demand, I'd go with IList.