Let me provide an example:
Suppose i have a method:
public void DoStuff(IEnumerable<T> sequence)
{
if (/* is lazy sequence */) throw ...
// Do stuff...
}
And I want to guard against potentially infinite sequences.
Edit:
To elaborate, guarding against infinite collection is only one of the uses. As Jon mentioned. You can easily have infinite IList. Good point.
Other use might be to detect whether data is potentially unrepeatable. Like a random generator. True collection has data already in memory and iterating it twice will give me same data.
There's nothing that's guaranteed, no. You could see whether the sequence also implements IList<T>
- that would prohibit iterator block implementations, but could still be a "virtual" list which continues forever, and it would also fail for some other finite non-iterator-block collections.
In terms of what you're trying to protect against, would a 2-billion-long sequence be okay for what you're trying to do? Would an extension method which threw an exception if you ended up with more than some "limit" (but do so lazily) work for you? (Something like Take, but which blew up at the end.)
This is impossible.
The IEnumerable API cannot possibly tell you whether it is infinite or not. You can try casting it to ICollection to catch the common case where someone has passed you one of those, but if that's what you want then why don't you take an ICollection<...> object in the first place?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With