Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collections use in foreach loop

Tags:

c#

.net

foreach

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,

like image 327
GETah Avatar asked Nov 11 '11 16:11

GETah


People also ask

Why forEach methods is added to each collection?

The forEach method was introduced in Java 8. It provides programmers a new, concise way of iterating over a collection. The forEach method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

What is the difference between collections forEach and streams forEach?

forEach takes the collection's lock once and holds it across all the calls to the action method. The Stream. forEach call uses the collection's spliterator, which does not lock, and which relies on the prevailing rule of non-interference.

Which interface is required for forEach collection?

Java forEach loop It is defined in Iterable and Stream interface. It is a default method defined in the Iterable interface. Collection classes which extends Iterable interface can use forEach loop to iterate elements.

What can forEach loops be used for?

The foreach loop in C# iterates items in a collection, like an array or a list. It proves useful for traversing through each element in the collection and displaying them. The foreach loop is an easier and more readable alternative to for loop.


3 Answers

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>.

like image 61
Jon Skeet Avatar answered Oct 16 '22 22:10

Jon Skeet


Short answer: it is only called once.

like image 38
Matt Fenwick Avatar answered Oct 16 '22 21:10

Matt Fenwick


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

like image 42
James Avatar answered Oct 16 '22 22:10

James