Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I return an IEnumerable or IList? [closed]

I wish to return an ordered list of items from a method. Should my return type be IEnumerable or IList?

like image 692
Ben Aston Avatar asked Jul 05 '10 15:07

Ben Aston


People also ask

Should I use 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.

Should I return IList or List?

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.

What is difference between IEnumerable and IList?

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.

What is the return type of IEnumerable?

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


2 Answers

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.

like image 69
Henk Holterman Avatar answered Sep 28 '22 04:09

Henk Holterman


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.

like image 35
Alex Humphrey Avatar answered Sep 28 '22 05:09

Alex Humphrey