22

What is the difference between choosing IEnumerable<T> vs IReadOnlyList<T> as a return parameter type or input parameter type?

IEnumerable<T> provides .Count and .ElementAt which is what is exposed by IReadOnlyList<T>

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Ramesh
  • 13,043
  • 3
  • 52
  • 88

1 Answers1

35

IEnumerable<T> represents a forward-only cursor over some data. You can go from start to end of the collection, looking at one item at a time.

IReadOnlyList<T> represents a readable random access collection.

IEnumerable<T> is more general, in that it can represent items generated on the fly, data coming in over a network, rows from a database, etc. IReadOnlyList<T> on the other hand basically represents only in-memory collections.

If you only need to look at each item once, in order, then IEnumerable<T> is the superior choice - it's more general.

I'd recommend actually looking at the C++ Standard Template Library - their discussion of the various types of iterators actually maps pretty well to your question.

Chris Tavares
  • 29,165
  • 4
  • 46
  • 63