开发者

C# foreach - Is collection computed with each iteration? [duplicate]

开发者 https://www.devze.com 2023-01-17 05:20 出处:网络
This question already has answers here: 开发者_开发知识库 Closed 12 years ago. Possible Duplicate:
This question already has answers here: 开发者_开发知识库 Closed 12 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消