views:

57

answers:

1

Are there any non-repeatable IEnumerable classes?

By non-repeatable I mean where you can't safely call GetEnumerator multiple times or where calling GetEnumerator has observable side effects.

+1  A: 

No, any well behaving class that implements IEnumerable will allow repeated enumerations.

To enumerate collections that aren't repeatable, you don't have a class that implements IEnumerable. Instead you have a method that returns an enumerator. That way the enumerator instead of a class holds the collection, so it's not possible to call GetEnumerator twice for the same collection. To repeat the enumerator you have to call the method to create a new collection.

An example of this is the Enumerable.Range method. It creates the items for a range on the fly, so the range doesn't exist as a collection, which makes it non-repeatable. To enumerate the same range again you call the method to create a new range with the same bounds.

Guffa
Enumerable.Range doesn't create the items at all, that is taken care of by Enumerable.Range.GetEnumerator. Since the enumerator it returns has the same intital values each time, it still would be considered repeatable.
Jonathan Allen
@Jonathan: You are missing the point. The range is not repeatable as you can't enumerate the same range again, you have to create a new range. Since the Range method doesn't return an enumerable object but an enumerator, there is no object that you can call GetEnumerator on to repeat the enumeration.
Guffa