Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Foreach Cache IEnumerable?

Tags:

c#

ienumerable

Supposing that SomeMethod has signature

public IEnumerable<T> SomeMethod<T>();

is there any difference between

foreach (T tmp in SomeMethod<T>()) { ... }

and

IEnumerable<T> result = SomeMethod<T>();

foreach (T tmp in result) { ... }

In other words, will the results of SomeMethod<T> be cached on the first statement or will it be evaluated upon each iteration?

like image 763
User Avatar asked Jul 14 '11 08:07

User


1 Answers

Assuming you're talking about C#.

foreach translates into something like this:

var enumerable = SomeMethod<T>(); // Or whatever is passed to foreach
var enumerator = enumerable.GetEnumerator();

while (enumerator.MoveNext())
{
...
}

So, as enumerable is needed only once, there will be only one call to SomeMethod even if you put it directly into the foreach statement.

like image 134
František Žiačik Avatar answered Sep 21 '22 16:09

František Žiačik