Supposing that SomeMethod
has signature
public IEnumerable SomeMethod();
is there any difference between
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.
An enumerATOR is generally a different type of object from an enumerABLE. Typically an enumerator will hold a reference to an enumerable object, along with some information about where it is in the process of enumeration. The purpose of an enumerable object is not actually to supply a sequence of items, but rather to supply an enumerator which will in turn supply the sequence.
In both vb.net and C#, the foreach construct works by calling a GetEnumerator method once on the object and grabbing the object it returns, repeatedly calling MoveNext and Current on the object returned from GetEnumerator, and finally, if that object implements Dispose, calling Dispose on it. Neither C# nor vb.net actually caches the enumerable object, but neither of them needs to use the object for any purpose after having called GetEnumerator on it once. Both languages do hold onto the enumerator, but neither provides any means of doing anything with it other than the implied calls to MoveNext, Current, and Dispose.