By reading similar posts I've learned that a List is a type of IEnumerable. But I'm really wondering what the practical difference between those two actually is.
To someone who always have used a List and never used IEnumerable:
Here is a practical example: We want to store four strings, order them alphabetically, pass them to another function and then show the user the result. What would we use and why?
Hopefully someone can sort this out for me or point me in the right direction. Thanks in advance!
IEnumerable is a deferred execution while List is an immediate execution. IEnumerable will not execute the query until you enumerate over the data, whereas List will execute the query as soon as it's called. Deferred execution makes IEnumerable faster because it only gets the data when needed.
We aren't forcing the caller to convert their data structure to a List unnecessarily. So it isn't that IEnumerable<T> is more efficient than list in a "performance" or "runtime" aspect. It's that IEnumerable<T> is a more efficient design construct because it's a more specific indication of what your design requires.
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.
List implements the interface Ienumerable.so it Includes all methods of IEnumerable.
One important difference between IEnumerable and List (besides one being an interface and the other being a concrete class) is that IEnumerable is read-only and List is not.
So if you need the ability to make permanent changes of any kind to your collection (add & remove), you'll need List. If you just need to read, sort and/or filter your collection, IEnumerable is sufficient for that purpose.
So in your practical example, if you wanted to add the four strings one at a time, you'd need List. But if you were instantiating your collection all at once, you could use IEnumerable.
IEnumerable firstFourLettersOfAlphabet = new[]{"a","b","c","d"};
You could then use LINQ to filter or sort the list however you wanted.
Many types other than List<T>
implement IEnumerable
such as an ArrayList
. So one advantage is you can pass different collection types to the same function.
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