Question:
In which case would it make sense for me to forgo iterating an array using "normal" loops ( for/foreach/while
) via index to use the IEnumerator
as shown in Example 3?
Example1
//Usando for
int[] array = new int[]{1, 2, 3, 4, 5 };
for ( int i = 0; i < array.Lenght; i++)
{
Console.WriteLine( array[i] );
}
Example2
//Usando foreach (Na prática o compilador gera um código bem parecido ao Exemplo1)
int[] array = new int[]{1, 2, 3, 4, 5};
foreach (int item in array)
{
Console.WriteLine(item);
}
Example3
//Via IEnumerator utilizando o loop while
int[] array = new int[]{1, 2, 3, 4, 5 };
IEnumerator o = array.GetEnumerator();
while (o.MoveNext())
{
Console.WriteLine(o.Current);
}
Answer:
If you know it's an array and it's a simple loop I don't see any reason to use IEnumerator
.
If you want to generalize the implementation and accept things other than an array as an implementation detail, then using an IEnumerable
might be interesting, but this would be used in something that doesn't know what's coming, so it would be a parameter or a method return . But it doesn't make sense in the example shown.
If you want to have a control, the enumeration outside the basic loop can also be interesting. With an enumerator it is possible to transport the state of the enumeration to other places in the code, passing it as an argument of a method, returning it in the current method, storing it as a member of some object, etc. It's rare to need something like this, but it's a way of doing more complex things. With index scanning the enumeration state only exists inside the loop.
using System;
using System.Collections;
public class Program {
static int[] array = new int[]{1, 2, 3, 4, 5 };
public static void Main() {
var o = Teste();
if (o != null) {
WriteLine("Continuando...");
while (o.MoveNext()) WriteLine(o.Current);
}
}
static IEnumerator Teste() {
IEnumerator o = array.GetEnumerator();
while (o.MoveNext()) {
WriteLine(o.Current);
if ((int)o.Current > 2) return o;
}
return null;
}
}
See working on ideone . And in .NET Fiddle . Also posted on GitHub for future reference .
If .NET were written today it would be different .