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.
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.)