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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With