tags:

views:

81

answers:

1

Possible Duplicate:
How does foreach work when looping through function results?

Title has the heart of the question in it. Here's an example scenario to flesh it out some more.

foreach(something thing in GetSomethings())
{ dosomething }

Lets say GetSomethings has side effects. Will GetSomethings be executed once or will it get executed for each time the loop iterates?

+6  A: 

Foreach uses IEnumerable interface, it retrieves the Enumerator once, and uses it to traverse the collection.

So it's perfectly safe to use foreach on a complex function, it doesn't re-calculate the collection each time.

Aren
thank you! Couldn't figure out where to look this up. Teach me to fish; is there any way I can look up how these control structures are implemented? Or more pointedly, how did you figure this out?
MushinNoShin
@Mush: http://msdn.microsoft.com/en-us/library/kx37x362.aspx, http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx, http://go.microsoft.com/fwlink/?LinkId=199552
John Saunders
If you read the MSDN Article about foreach: http://msdn.microsoft.com/en-us/library/ttw7t8t6(v=VS.71).aspx it mentions the method it uses. MSDN is a very good resource for learning about the operation of language features / classes in .NET.
Aren
@MushinNoShin: The language specification is available on the internet and in book form.
Eric Lippert
You should research the *yield* operator and how it functions during enumeration.
Michael