views:

152

answers:

3

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.

+5  A: 

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.

http://stackoverflow.com/questions/376708/ilist-vs-ienumerable-for-collections-on-entities

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

Kevin
+10  A: 

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.

On of the nice additions you get from staying on 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.

Rob Levine
I agree with using the least derived type. ICollection<> is sufficient for most adding/removing.
Mark H
@Mark H - good point - for most add/remove operations, even IList is unnecessarily specific.
Rob Levine
+1  A: 

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.

Restuta