Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical difference between List and IEnumerable [duplicate]

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:

  • What is the practical difference between the two?
  • In what scenarios is one of them better than the other?

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!

like image 653
Robin Avatar asked Jul 03 '13 13:07

Robin


People also ask

What is the difference between List and IEnumerable?

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.

Why we use IEnumerable instead of List?

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.

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.

Does List implement IEnumerable?

List implements the interface Ienumerable.so it Includes all methods of IEnumerable.


2 Answers

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.

like image 140
Scott Lawrence Avatar answered Oct 21 '22 22:10

Scott Lawrence


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.

like image 26
DasDave Avatar answered Oct 21 '22 23:10

DasDave