Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does foreach work when looping through function results?

Tags:

c#

.net

foreach

Suppose I have the following code:

foreach(string str in someObj.GetMyStrings()) {     // do some stuff } 

Will someObj.GetMyStrings() be called on every iteration of the loop? Would it be better to do the following instead:

List<string> myStrings = someObj.GetMyStrings(); foreach(string str in myStrings) {     // do some stuff } 

?

like image 437
Adam Lear Avatar asked Oct 27 '09 18:10

Adam Lear


People also ask

How does a forEach loop work?

How Does It Work? The foreach loop in C# uses the 'in' keyword to iterate over the iterable item. The in keyword selects an item from the collection for the iteration and stores it in a variable called the loop variable, and the value of the loop variable changes in every iteration.

What does a forEach loop return?

The forEach method does not return a new array like other iterators such as filter , map and sort . Instead, the method returns undefined itself.

What does the forEach function do?

forEach() The forEach() method executes a provided function once for each array element.


1 Answers

The function's only called once, to return an IEnumerator<T>; after that, the MoveNext() method and the Current property are used to iterate through the results:

foreach (Foo f in GetFoos()) {     // Do stuff } 

is somewhat equivalent to:

using (IEnumerator<Foo> iterator = GetFoos().GetEnumerator()) {     while (iterator.MoveNext())     {         Foo f = iterator.Current;         // Do stuff     } } 

Note that the iterator is disposed at the end - this is particularly important for disposing resources from iterator blocks, e.g.:

public IEnumerable<string> GetLines(string file) {     using (TextReader reader = File.OpenText(file))     {         string line;         while ((line = reader.ReadLine()) != null)         {             yield return line;         }     } } 

In the above code, you really want the file to be closed when you finish iterating, and the compiler implements IDisposable cunningly to make that work.

like image 117
Jon Skeet Avatar answered Oct 21 '22 00:10

Jon Skeet