I end up with a lot of code like this:
List<string> dates = someMethodCall();
foreach (string dateStr in dates) { }
I usually declare the object over which I'm iterating and then use it in the foreach
condition out of worry that someMethodCall()
would happen for each iteration of the loop. Is this the case? I would prefer to do this:
foreach (string dateStr in someMethodCall()) { }
But I only want to do that if someMethodCall()
happens only once and then its results are cached for each subsequent iteration.
The method will be called only once in both cases.
The first method has a readability advantage as you can name the variable and describe what's in it with its name. It will make the code more self-documenting and improves maintainability.
To quote the authoritative source on this:
C# Language Specification - 8.8.4 The
foreach
statementforeach (V v in x) embedded-statement
is then expanded to:
{ E e = ((C)(x)).GetEnumerator(); try { V v; while (e.MoveNext()) { v = (V)(T)e.Current; embedded-statement } } finally { … // Dispose e } }
It's clear that the expression x
in the above foreach
statement is evaluated only once in the expansion.
foreach
will evaluate the collection once, get the iterator, and then use that for its iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With