What should I use an IEnumerable or IList?

Sergio Tapia picture Sergio Tapia · Jul 12, 2010 · Viewed 34.3k times · Source

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.

Answer

Rob Levine picture Rob Levine · Jul 12, 2010

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.