Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable<T> vs IReadOnlyList<T>

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>

like image 247
Ramesh Avatar asked Jan 09 '15 06:01

Ramesh


People also ask

What is IReadOnlyList?

The IReadOnlyList<T> represents a list in which the number and order of list elements is read-only.

When to use ICollection vs IEnumerable?

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.

What is the difference between ICollection and IEnumerable?

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.

Is IEnumerable readonly?

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.


1 Answers

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.

like image 68
Chris Tavares Avatar answered Oct 13 '22 05:10

Chris Tavares