Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 314
Sergio Tapia Avatar asked Jul 12 '10 12:07

Sergio Tapia


People also ask

Should I return IEnumerable or IList?

Generally, it's better to return IEnumerable<T> , as long as that has everything the caller needs.

What is the difference between IList and IEnumerable?

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.

Is IEnumerable more efficient than list?

IEnumerable is more efficient and faster when you only need to enumerate the data once. The List is more efficient when you need to enumerate the data multiple times because it already has all of it in memory.

When should I use IEnumerable in C#?

IEnumerable interface is used when we want to iterate among our classes using a foreach loop. The IEnumerable interface has one method, GetEnumerator, that returns an IEnumerator interface that helps us to iterate among the class using the foreach loop.


1 Answers

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.

like image 157
Rob Levine Avatar answered Sep 20 '22 07:09

Rob Levine