mshvw

Hello,

I'm trying to understand the 'foreach' statement and the IEnumerator interfacing.

I run code like:

foreach(MyCitizenType x in MyCity){}

In the associated IEnumerator class, inside the 'Reset', 'MoveNext' and 'Current' memberfunctions I put some Console.WriteLine output. During debugging then at the first time that 'MyCity' is accessed, the IEnumerable GetEnumerator function is called. That seems okay to me ;-)

Then with each run through 'foreach' the 'MoveNext' memberfunction is executed followed by the 'Current' function until 'MoveNext' returns false then the 'Current' function is not executed and the foreach loop exits. So far so good...

But never do I see the 'Reset' function being executed. I was thinking that prior to any 'foreach' execution the 'Reset' function should be called by the operating system.

Also when executing two consequtive 'foreach' statements no 'Reset' function is executed.

Where do I go wrong in my way of thinking

regards,

Henk



Re: Visual C# Language IEnumerator: Why is 'foreach' Reset memberfunction not executed?

Robert C. Barth

When GetEnumerator() is called, the enumerator is positioned before the first element (from the docs: "Initially, the enumerator is positioned before the first element in the collection").

Each individual foreach loop calls GetEnumerator() anew, so the new enumerator is positioned before the first element each time.





Re: Visual C# Language IEnumerator: Why is 'foreach' Reset memberfunction not executed?

Sean Hederman

Yeah, the foreach statement does not support resetting the enumeration, even though IEnumerator does.