GETah
GETah

Reputation: 21449

Collections use in foreach loop

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

Answers (3)

James
James

Reputation: 2911

It gets called once and will generate an exception if the collection is modified.

Upvotes: 2

Jon Skeet
Jon Skeet

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

Matt Fenwick
Matt Fenwick

Reputation: 49105

Short answer: it is only called once.

Upvotes: 6

Related Questions