Iterate an array (vector) via IEnumerator? For what reason?

3

In what case would it make sense for me to forgo an array using loops "normal" ( for/foreach/while ) via index to use 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);    
      }
    
asked by anonymous 20.03.2017 / 12:10

1 answer

2

If you know that it is an array and it is a simple loop I see no reason to use IEnumerator .

If you want to generalize the implementation and accept things other than a array as an implementation detail, then using IEnumerable might be interesting, but this would be used in something that does not know what will come, then it would be a parameter or the return of a method. But it does not 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 carry the state of the enumeration to other places of the code, passing 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 that, but it's a way of doing more complex things. With index scanning the enumeration state exists only 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) {
            Console.WriteLine("Continuando...");
            while (o.MoveNext()) {
                Console.WriteLine(o.Current);
            }   
        }
    }
    static IEnumerator Teste() {
        IEnumerator o = array.GetEnumerator();
        while (o.MoveNext()) {
            Console.WriteLine(o.Current);
            if ((int)o.Current > 2) {
                return o;
            }
        }
        return null;
    }
}

See running on .NET Fiddle . And No Coding Ground . Also put it on GitHub for future reference .

If .NET were written today would be different .

    
20.03.2017 / 12:48