What should I use an IEnumerable or IList?

C#IenumerableIlist

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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 - C#

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.

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

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

Solution 3 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSergio TapiaView Question on Stackoverflow
Solution 1 - C#Rob LevineView Answer on Stackoverflow
Solution 2 - C#kemiller2002View Answer on Stackoverflow
Solution 3 - C#RestutaView Answer on Stackoverflow