Dinerdo Dinerdo - 1 year ago 52
C# Question

Is there a difference between using foreach to iterate through a collection stored in a variable or returned in a method?

This is a silly question, but I'm stuck when trying to confirm the answer.

I haven't stepped through this recently, but I previously struggled in determining if the return value was being stored for a constant iterator or if the method was being evaluated again each time with some sort of "skip" in place.

Ex. A

foreach(var c in chars)
// do work

Ex. B

foreach(var c in GetChars(x))
// do work

EDIT: I do not have access to Visual Studio for the time being. If there are other reasons for the down vote, please explain.

Answer Source

No, the GetChars(x) would be evaluated for only one time.

Hence, I believe both are similar.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download