Reputation: 21449
I am iterating through a collection in a foreach loop and was wondering. When this gets executed by the .NET runtime
foreach (object obj in myDict.Values) {
//... do something
}
Does the myDict.Values get invoked for every loop or is it called only once?
Thanks,
Upvotes: 5
Views: 663
Reputation: 2911
It gets called once and will generate an exception if the collection is modified.
Upvotes: 2
Reputation: 1503539
Just once. It's roughly equivalent to:
using (IEnumerator<Foo> iterator = myDict.Values.GetEnumerator())
{
while (iterator.MoveNext())
{
object obj = iterator.Current;
// Body
}
}
See section 8.8.4 of the C# 4 spec for more information. In particular, details about the inferred iteration element type, disposal, and how the C# compiler handles foreach
loops over types which don't implement IEnumerable
or IEnumerable<T>
.
Upvotes: 9