I was wondering if there are any times where it’s advantageous to use an IEnumerator over a foreach loop for iterating through a collection? For example, is there any time where it would be better to use either of the following code samples over the other?
IEnumerator<MyClass> classesEnum = myClasses.GetEnumerator(); while(classesEnum.MoveNext()) Console.WriteLine(classesEnum.Current);
instead of
foreach (var class in myClasses) Console.WriteLine(class);
First, note that one big difference in your example (between
foreachandGetEnumerator) is thatforeachguarantees to callDispose()on the iterator if the iterator isIDisposable. This is important for many iterators (which might be consuming an external data feed, for example).Actually, there are cases where
foreachisn’t as helpful as we’d like.First, there is the ‘first item’ case discussed here (foreach / detecting first iteration).
But more; if you try writing the missing
Zipmethod for stitching two enumerable sequences together (or theSequenceEqualmethod), you find that you can’ useforeachon both sequences, since that would perform a cross-join. You need to use the iterator directly for one of them: