What's the difference between IEnumerable<T> and List<T>?
Short answer
IEnumerable is an interface representing a sequence of items that can be enumerated one at a time using deferred execution, meaning the actual data is only produced when you iterate over it, which makes it memory efficient for large or streaming data sources.
Advertisement
AModel answer
IEnumerable<T> is an interface representing a sequence of items that can be enumerated one at a time using deferred execution, meaning the actual data is only produced when you iterate over it, which makes it memory efficient for large or streaming data sources. List<T> is a concrete class that implements IEnumerable<T> but stores all of its items in memory at once, and it also provides additional capabilities like adding, removing, sorting, and accessing items directly by index, which IEnumerable<T> alone does not support.
IEnumerable<int> numbers = GetNumbersLazily();
List<int> list = numbers.ToList();
list.Add(10);
var first = list[0];Real-world example
A reporting feature that processes millions of database records uses IEnumerable<T> to stream results one at a time and avoid loading everything into memory, only converting the relevant filtered subset into a List<T> for further manipulation.
Likely follow-ups
- What does deferred execution actually mean in practice?
- When should you convert an IEnumerable to a List?
Related topics