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?
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?
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.
Nope, it doesn't. EventLocator.GetTypes()
will be optimized by compiler to a variable in outer scope