Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach in C# recalculation

Tags:

c#

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?

like image 914
Haim Bender Avatar asked Oct 04 '09 23:10

Haim Bender


4 Answers

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.

like image 106
Eric Lippert Avatar answered Oct 02 '22 18:10

Eric Lippert


It will only calculate it once

like image 27
Dinah Avatar answered Oct 02 '22 19:10

Dinah


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.

like image 28
Yuriy Faktorovich Avatar answered Oct 02 '22 20:10

Yuriy Faktorovich


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.

like image 24
Timothy Carter Avatar answered Oct 02 '22 20:10

Timothy Carter