Search code examples
c#.netienumerableicollection

What is the real advantage of returning ICollection<T> instead of a List<T>?


I've read a couple of blog post mentioning that for public APIs we should always return ICollection (or IEnumerable) instead of List. What is the real advantage of returning ICollection instead of a List?

Thanks!

Duplicate: What is the difference between List (of T) and Collection(of T)?


Solution

  • An enumerator only returns one entity at a time as you iterate over it. This is because it uses a yield return. A collection, on the other hand, returns the entire list, requiring that the list be stored completely in memory.

    The short answer is that enumerators are lighter and more efficient.