Is IE IE cache list cached?

Suppose SomeMethod has a 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 in the first expression, or will they be evaluated at each iteration?

+4
source share
2 answers

Assuming you're talking about C #.

foreach means the following:

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

So, since enumerable is required only once, there will be only one call to SomeMethod, even if you put it directly in the foreach .

+13
source

EnumerATOR is usually another type of enumerated object. Typically, an enumerator will contain a link to an enumerated object, as well as some information about where it is in the enumeration process. The purpose of an enumerated object is not to supply a sequence of elements, but to supply an enumerator, which in turn will provide a sequence.

In both vb.net and C #, the foreach constructor works by calling the GetEnumerator method once on the object and capturing the returned object, repeatedly calling MoveNext and Current on the object returned from GetEnumerator, and finally, if this object implements Dispose by calling Dispose on it . Neither C # nor vb.net actually caches an enumerated object, but none of them should use the object for any purpose after it once called GetEnumerator. Both languages ​​are stored in the enumerator, but none of them provides any means for anything with it, except for the implied calls to MoveNext, Current and Dispose.

0
source

All Articles