I wish to return an ordered list of items from a method. Should my return type be IEnumerable or IList?
You use IEnumerable when you want to loop through the items in a collection. IList is when you want to add, remove, and access the list contents out of order.
Generally best practice is to accept parameters of the most generic type and to return the most specific. However, conventionally programmers tend to not want to tie themselves to the List implementation and normally return the IList interface.
IList doesn't support further filtering. IEnumerable exists in System. Collections Namespace. IEnumerable is a forward only collection, it can't move backward and between the items.
IEnumerable has just one method called GetEnumerator. This method returns another type which is an interface that interface is IEnumerator. If we want to implement enumerator logic in any collection class, it needs to implement IEnumerable interface (either generic or non-generic).
There is a hierarchy here:
interface IList<T> : ICollection<T> { } interface ICollection<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With