What should I use an IEnumerable or IList? [duplicate]

Can anyone tell me when I should use either.

For example, I think I should use an IList when I want to access the .Count of the collection or an individual item, correct?

Thank you.


Solution 1:

Generally speaking, you should try and use the least specific type that suits your purpose. IEnumerable is less specific than IList (IList implements IEnumerable) so unless you want something specific from IList (such as Count as you suggest, or perhaps Add, Delete, etc), I'd use IEnumerable.

One benefit of remaining with IEnumerable is that you can write iterator methods to return this type (look up "yield return" and iterator methods if you are not familiar with them). This allows you to write very memory efficient "pipelines" for your loops.

Solution 2:

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.

IList vs IEnumerable for Collections on Entities

http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=722

Solution 3:

You should use IList when you need access by index to your collection, add and delete elements, etc., and IEnumerable when you need just enumerate over your collection.

A very simple answer, I can extend it if you will describe you scenario.