If I use yield instead of manually creating an IEnumerator, is it possible to implement IEnumerator.Reset?
There's a nice workaround that I just discovered. Make your generator method return IEnumerable
, not IEnumerator
. Then you can do
var values = MyGeneratorMethod();
var enumerator = values.GetEnumerator();
// ... do stuff with enumerator
enumerator = values.GetEnumerator(); // instead of enumerator.Reset();
I believe itowlson's answer suggested this exact trick, but I couldn't understand it until I heard of the trick elsewhere.