Practical difference between List and IEnumerable

C#.NetListIenumerable

C# Problem Overview


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!

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobinView Question on Stackoverflow
Solution 1 - C#Scott LawrenceView Answer on Stackoverflow
Solution 2 - C#DasDaveView Answer on Stackoverflow