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,
Just once. It’s roughly equivalent to:
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
foreachloops over types which don’t implementIEnumerableorIEnumerable<T>.