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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With