3

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?

Community
  • 1
  • 1
MushinNoShin
  • 4,695
  • 2
  • 32
  • 46
  • Please stop answering this duplicate question. – John Saunders Sep 21 '10 at 19:56
  • @anna lear; it certainly is a duplicate question. Title might be a little more succinct than simply "how does foreach work when iterating." – MushinNoShin Sep 21 '10 at 20:00
  • 2
    I note that this question is trivial to answer yourself; just have GetSomethings return a collection of ten elements and print to the console. If it prints once, then it is fetched once. If it prints ten times then it is fetched once per iteration. – Eric Lippert Sep 21 '10 at 20:04

1 Answers1

10

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
  • 54,668
  • 9
  • 68
  • 101
  • 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 Sep 21 '10 at 19:57
  • @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 Sep 21 '10 at 19:59
  • 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 Sep 21 '10 at 20:01
  • @MushinNoShin: The language specification is available on the internet and in book form. – Eric Lippert Sep 21 '10 at 20:03
  • You should research the *yield* operator and how it functions during enumeration. – Michael Sep 22 '10 at 01:56