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?
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.
精彩评论