IEnumerable vs IReadOnlyList

2020-08-19 03:02发布

问题:

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>

回答1:

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.