If I use yield instead of manually creating an IEnumerator, is it possible to implement IEnumerator.Reset?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There is no built-in support, but you can define your own implementation of
IEnumeratorthat delegates all method calls to the enumerator generated by C# and only lets you define your own behavior for theResetmethod.The simplest version of the class would look like this:
In this case, the
ResetFuncthat you specify returns a newIEnumerator<T>, so your provided implementation ofResetFunccan do some cleanup or whatever you need to do when resetting and then return a new enumerator.You’ll need to store all the originally local variables of the
Foomethod as fields of the class, so that you can access them inCleanup(Note that the rest of theFoobody will never be executed after callingReset), but that’s still easier than writing a handwritten iterator!