Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit to using List<T> over IEnumerable<T>?

or the other way around?

I use generic lists all the time. But I hear occasionally about IEnumerables, too, and I honestly have no clue (today) what they are for and why I should use them. So, at the risk of having something on the net forever more proclaiming my ignorance, I humbly post this question.

like image 970
Byron Sommardahl Avatar asked Nov 09 '09 15:11

Byron Sommardahl


2 Answers

Well, List<T> implements IEnumerable<T>... basically IEnumerable<T> is just a sequence of items. You can read through it, and that's all.

List<T> is a mutable collection - you can add to it, remove from it, sort it etc. It's more flexible in itself, but IEnumerable<T> allows you to use the same code to work with any implementation (arrays, linked lists, lists, iterators returned from methods using yield statements etc).

like image 107
Jon Skeet Avatar answered Oct 09 '22 12:10

Jon Skeet


IEnumerable<T> is a more general interface, so you can substitute anything that implements that interface for your operation. If you have this method:

public void DoSomething(IEnumerable<T> enumerable) {
}

It will work on arrays, collections, lists, dictionaries, and anything else that implements the interface.

If you specify that the object is a List<T>, the method will only work on List<T> objects or instances that inherit from it.

The advantage of using List<T> is that lists have many more features than enumerables. When you need those features (insertion, searching, conversion, and many more), List<T> or IList<T> is more appropriate.

like image 29
Jeff Sternal Avatar answered Oct 09 '22 10:10

Jeff Sternal