2

I came across this in our codebase:

foreach (var evtType in EventLocator.GetTypes())

and remembering Shlemiel the painter's algorithm does the method EventLocator.GetTypes() get called on each loop or just the once?

Kevin Pluck
  • 641
  • 5
  • 14
  • This is also relevant, but closed as duplicate: [How is foreach implemented in C#?](http://stackoverflow.com/q/11179156/7586) – Kobi May 20 '15 at 11:36
  • @Kobi I can see why you marked this as a duplicate but I couldn't see the answer to my question in the answer you linked as I wanted to know if the method that returns a collection is called on each loop or just the once. All the examples in the question you linked used prefabricated collections that weren't returned from a method. – Kevin Pluck May 20 '15 at 11:45
  • I only closed after making sure [the answer](http://stackoverflow.com/a/398996/7586) is there, under "A foreach loop [...] kinda equates to". `var tmp = obj.GetEnumerator();` shows the method is only called once, to create an enumerator. – Kobi May 20 '15 at 12:02

2 Answers2

13

The expession designating collection being iterated is conceptually captured into a local variable before the loop starts. It is executed only once.

You can derive this fact just by logic. Imagine the source was an IEnumerable<T> that is stateful. How would you continue the loop if you discarded the old object and reexecuted the source expression? You can't index into a sequence.

usr
  • 168,620
  • 35
  • 240
  • 369
0

Nope, it doesn't. EventLocator.GetTypes() will be optimized by compiler to a variable in outer scope

Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
Alex Voskresenskiy
  • 2,143
  • 2
  • 20
  • 29