If I write a foreach statment in C#:
foreach(String a in veryComplicatedFunction())
{
}
Will it calculate veryComplicatedFunction every iteration or only once, and store it somewhere?
Your question is answered by section 8.8.4 of the specification, which states:
The above steps, if successful, unambiguously produce a collection type C, enumerator type E and element type T. A foreach statement of the form
foreach (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
}
}
As you can see, in the expansion the expression x is only evaluated once.
It will only calculate it once
It depends on what you mean by once. If you have a method like the following:
public static IEnumerable<int> veryComplicatedFunction()
{
List<string> l = new List<string> { "1", "2", "3" };
foreach (var item in l)
{
yield return item;
}
}
Control would be returned to the method calling veryComplicatedFunction after each yield. So if they were sharing List l then you could have some strange results. A sure fire way to remove that kind of problem would be calling the ToArray extension on the veryComplicatedFunction.
veryComplicatedFunction
likely returns IEnumerable<string>
, which should mean that it's calculations are performed only once and it streams its results in some way. However, without seeing the actual method, there is no way to guarantee what it does. What is guaranteed is that veryComplicatedFunction
is only called once, what the foreach
does is iterate through the returns of a method.
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