86

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!

Robin
  • 1,927
  • 3
  • 18
  • 27
  • 2
    A `List` isn't a type of `IEnumerable` it fulfills the contract that `IEnumerable` sets out (i.e. it can be used as an `IEnumerable`). If you want to store strings you'd use a list. You couldn't use an enumerable as that isn't a class. You could access the list as an enumerable if you wanted. – George Duckett Jul 03 '13 at 13:06
  • 13
    This shouldn't be marked as a duplicate question. The other question talks about IEnumberable vs List when using LINQ. This question is not about LINQ. – iheartcsharp Jan 10 '17 at 14:50
  • List allows random access but IEnumerable doesn't – Binoy Kumar Jan 25 '19 at 09:34

2 Answers2

240

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.

Scott Lawrence
  • 6,993
  • 12
  • 46
  • 64
  • 3
    There are some other cool things you can do with IEnumerable that you can't do with a List. Check out the yield keyword. https://www.kenneth-truyers.net/2016/05/12/yield-return-in-c/ – Kevin Aug 14 '17 at 22:33
16

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.

d219
  • 2,707
  • 5
  • 31
  • 36
DasDave
  • 801
  • 1
  • 9
  • 28