Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for IEnumerable/IEnumerable<T> interfaces to only have MoveNext?

Basically I am wondering why MS decided to implement an enumerator that only supports going forward: MoveNext().

Is it not more flexible to also enforce MovePrevious for this widely used interface throughout the .NET framework?

I can imagine it making the Linq.Reverse far easier to implement for MS and more efficient in performance, but I am not sure if this makes other things slower or puts a massive overhead on everything else.

Anyone with more knowledge in this subject can give more info on this please? i.e. the pros and cons of having or not having MovePrevious in IEnumerable/IEnumerable<T>.

like image 743
Joan Venge Avatar asked Nov 26 '09 23:11

Joan Venge


1 Answers

IEnumerable[<T>] represents a sequence of data, not a random-access list. Not all sequences can be reversed, or even replayed. Sequences based on network streams, database access, etc - or this beauty:

IEnumerable<int> GetData() {
    Random rand = new Random();
    while(true) { yield return rand.Next(); }
}

The best you can do is start again - not by calling Reset() (which is deprecated), but by getting a fresh enumerator instead.

Even without Random it is trivial to come up with simple sequences that cannot be reversed (without buffering and reversing the buffer). For what you want, consider looking at IList[<T>] instead - you can access data via the indexer in any order.

like image 76
Marc Gravell Avatar answered Oct 06 '22 00:10

Marc Gravell