Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does foreach resolve the container?

Tags:

c#

.net

foreach

foreach(Value v in myDictionary[key])

In this scenario, is the compiler able to determine that myDictionary[key] will always be the same and not hash the [key] every iteration of foreach?

foreach(Value v in myEnumerable.Where(s => s.IsTrue))

I know enumerables are lazy, I suspect that in this case, the .Where only resolves once and returns a full collection for the foreach but that is only a hunch.

Judging by this question, the foreach is doing a .GetEnumerable even in scenario 1, so its the return of that which is used so therefore it only resolves once and not on every iteration.

like image 844
user99999991 Avatar asked Mar 22 '26 05:03

user99999991


1 Answers

foreach in C# is just a syntactic sugar.

foreach (V v in x) embedded-statement

gets expanded into

{
    E e = ((C)(x)).GetEnumerator();
    try {
        while (e.MoveNext()) {
            V v = (V)(T)e.Current;
            embedded-statement
        }
    }
    finally {
        … // Dispose e
    }
}

As you can see, x is only used once, to get the enumerator by calling GetEnumerator on it. So your dictionary lookup will only be executed once. Later on it does only care about that enumerator, not where it came from.

like image 195
MarcinJuraszek Avatar answered Mar 24 '26 19:03

MarcinJuraszek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!