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>
The IReadOnlyList<T> represents a list in which the number and order of list elements is read-only.
If we want some more functionality like Add or remove element, then it is better to go with ICollection because we cannot achieve that with IEnumerable. ICollection extends IEnumerable. It supports non-index based operations like - Add item in Collection, remove, check contained item etc.
IEnumerable has one property: Current, which returns the current element. ICollection implements IEnumerable and adds few additional properties the most use of which is Count. The generic version of ICollection implements the Add() and Remove() methods.
IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With