Practical difference between List and IEnumerable

Robin picture Robin · Jul 3, 2013 · Viewed 81.3k times · Source

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!

Answer

Scott Lawrence picture Scott Lawrence · Jul 3, 2013

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.