Is there a way to determine if an IEnumerable <T> is a sequence generator or a true collection?

Let me give an example:

Suppose I have a method:

public void DoStuff(IEnumerable<T> sequence) { if (/* is lazy sequence */) throw ... // Do stuff... } 

And I want to protect against potentially infinite sequences.

Edit:

To develop, protection from an endless collection is just one use. As John said. You can easily have an infinite Eilist. Good point.

Another use may be to detect potentially inappropriate data. Like a random generator. A true collection has data already in memory, and repeating it twice will give me the same data.

+4
source share
3 answers

Iterators do not support the IEnumerable <> method. Reset ():

 public void DoStuff(IEnumerable<T> sequence) { sequence.Reset(); // etc.. } 

You get a NotSupportedException, which is good, because the message "The specified method is not supported" is valid.

+1
source

There is nothing guaranteed, no. You could see if the sequence also implements IList<T> , which prohibits the implementation of an iterator block, but it can still be a "virtual" list that lasts forever, and it also fails for some other finite collections of non-iterative blocks.

In terms of what you are trying to protect, will the 2 billion sequence be long in order, what are you trying to do? Will there be an extension method that throws an exception if you had more than a certain β€œlimit” (but do it lazily), work for you? (Something like Take, but that exploded at the end.)

+5
source

It's impossible.

The IEnumerable API cannot tell you whether it is infinite or not. You can try sending it to ICollection in order to catch the general case when someone passed one of them to you, but if this is what you want, then why not take the ICollection <... object first?

+5
source

All Articles