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

Asked

Viewed 121 times

3

In which case it would make sense for me to give up iterating a array using loops "normal" (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] );     
    }

Exemplo2

//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);    
      }

1 answer

2


If you know it’s a array and it’s a simple tie I don’t see any reason to use IEnumerator.

If you want to generalize implementation and accept other things than one array as implementation detail, then use a IEnumerable might be interesting, but this would be used on something that doesn’t know what’s coming, so it would be a parameter or the return of a method. But it makes no 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 argument of a method, return it in the current method, store as member of some object, etc. It is rare to need something like this, but it is a way of doing more complex things. With index scanning the enumeration state only exists within 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;
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

If . NET were written today it would be different.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.