• Advertisement
Sign in to follow this  

[.net] c# foreach

This topic is 4705 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am trying to make a class work correctly as an IEnumerable. In what order are IEnumerable's methods called when a foreach loop is being executed?

Share this post


Link to post
Share on other sites
Advertisement
Well, GetEnumerator is called to retrieve an instance of the enumerator from something that implements IEnumerable...

After that, it's going to be MoveNext then Current.

The initial state of something that implements IEnumerator is supposed to be that the pointer is before the first element in the enumeration. The initial MoveNext would move it to the first element.

For more information, look in MSDN under IEnumerator interface->about IEnumerator interface in the Remarks section.

Share this post


Link to post
Share on other sites
Okay, thanks.

A book I was looking at today had a "Reset" function, which confused me.

You are saying that MoveNext() is called before any data is retrieved? That's what it looks like from my code, but it doesn't make much sense.

Share this post


Link to post
Share on other sites
Okay, I understand now. The book I was using had a typo in their reset function, but it makes sense now.

Thanks for replying (I'm having to learn C# very quickly, so I'm sorry for dumping this simple question onto you.

edit: the typo was resetting the position to 0 instead of 1

Share this post


Link to post
Share on other sites
foreach is essentially a shortcut way of doing the following pseudocode:

While Enumerator.MoveNext
Do something with Enumerator.Current
End While

MoveNext returns "false" if there are no values left.

Reset moves the pointer into whatever you are enumerating back to before the first entry.

So if you have the following array:

0 1 2 3

And you are foreach'ing through it, the enumerator is pointing to whatever is before 0 when it is created. MoveNext moves it to 0. Reset moves it back to whatever is before 0.

Share this post


Link to post
Share on other sites
In the book I was using (which is very good otherwise), it has the position being reset to 0 instead of -1, and I couldn't figure out why (it was a typo). I'll post the book tommorow; I recommend everyone read it.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement