Why can't I get the Current value when I implemented IEnumerable?

I did the work below

class Program
{
    class GenEnumerator<T> : IEnumerable
    {
        public T[] Values { get; set; }


        public IEnumerator GetEnumerator()
        {
            for (int i = 0; i < Values.Length; i++)
                yield return Values[i];
        }
    }

    static void Main(string[] args)
    {
        GenEnumerator<string> g = new GenEnumerator<string>();
        g.Values = new string[] { "a", "b", "c", "d", "e" };
        g.GetEnumerator().MoveNext();

        Console.WriteLine(g.GetEnumerator().Current);


        Console.ReadKey();
    }
}

g.GetEnumerator().Currentalways zero.
but if I do - var a = g.GetEnumerator();
Current proeperty gets the value and works fine

Does this mean that I should explicitly inherit the class from IEnumeratorand implement its methods and property if I want to use Currentwithout a type variable IEnumerator?

Thanks Roy

+4
source share
2 answers

This is due to the fact that in order to Currentbecome non-zero, you need to call MoveNext()on the same object.

Your current code calls MoveNext()on a temporary object. This is what happens when you call

g.GetEnumerator().MoveNext()`;
Console.WriteLine(g.GetEnumerator().Current);
  • GetEnumerator() x
  • x.MoveNext()
  • x , .
  • g.GetEnumerator().Current, y
  • y.Current, null, MoveNext y

a, MoveNext Current , :

  • GetEnumerator() x, a
  • a.MoveNext()
  • a.Current
+4

GenEnumerator , GetEnumerator, Current - null. .

var e = g.GetEnumerator();
if(e.MoveNext())
{
    var current = e.Current;
}
+5

All Articles