A function called only once returns IEnumerator<T> ; after that, the MoveNext() method and the Current property are used to repeat the results:
foreach (Foo f in GetFoos()) {
somewhat equivalent:
using (IEnumerator<Foo> iterator = GetFoos().GetEnumerator()) { while (iterator.MoveNext()) { Foo f = iterator.Current;
Note that the iterator is located at the end - this is especially important for allocating resources from iterator blocks, for example:
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 the iteration, and the compiler implements IDisposable cunningly to make this work.
Jon Skeet Oct 27 '09 at 19:25 2009-10-27 19:25
source share