Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't IEnumerable<T> implement Add(T)?

Just now find it by chance, Add(T) is defined in ICollection<T>, instead of IEnumerable<T>. And extension methods in Enumerable.cs don't contain Add(T), which I think is really weird. Since an object is enumerable, it must "looks like" a collection of items. Can anyone tell me why?

like image 853
Cheng Chen Avatar asked Aug 27 '10 08:08

Cheng Chen


People also ask

Can you add to IEnumerable?

IEnumerable is only to view the contents of a collection. If you really want to add, convert the collection to List and then add items to the list.

What is IEnumerable T?

IEnumerable. IEnumerable<T> contains a single method that you must implement when implementing this interface; GetEnumerator, which returns an IEnumerator<T> object. The returned IEnumerator<T> provides the ability to iterate through the collection by exposing a Current property.

What is IEnumerable <> in C#?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.

Why do we use IEnumerable in C#?

IEnumerable is best to query data from in-memory collections like List, Array etc. IEnumerable doesn't support add or remove items from the list. Using IEnumerable we can find out the no of elements in the collection after iterating the collection. IEnumerable supports deferred execution.


2 Answers

An IEnumerable<T> is just a sequence of elements; see it as a forward only cursor. Because a lot of those sequences are generating values, streams of data, or record sets from a database, it makes no sense to Add items to them.

like image 138
Steven Avatar answered Oct 20 '22 00:10

Steven


IEnumerable is for reading, not for writing.

like image 41
Brian Avatar answered Oct 20 '22 01:10

Brian