This is because in order for the Current
to become non-null, you need to call MoveNext()
on the same object.
Your current code calls MoveNext()
on a temporary object. Here is what's going on when you call
g.GetEnumerator().MoveNext()`;
Console.WriteLine(g.GetEnumerator().Current);
- A call of
GetEnumerator()
returns an objectx
- A call
x.MoveNext()
is performed x
becomes eligible for garbage collection, because it is not referenced from any variable in your program.- When you call
g.GetEnumerator().Current
, a new objecty
is returned - A call to
y.Current
is made, returningnull
, because there was no call ofMoveNext
on objecty
When you add a variable a
, however, you call MoveNext
and Current
on the same object, fixing the problem:
- A call of
GetEnumerator()
returns an objectx
, which is assigned to variablea
- A call
a.MoveNext()
is performed - A call
a.Current
is performed