How this part of code is working
-
18-09-2020 - |
Question
UPD. Hello, I know how code below is working. I know that cross, and circle are pointing to Cross(), and Circle() method. But I am still filling little confuse with this part of code. Can you explain it for me?
public GameMoves()
{
cross = Cross();
circle = Circle();
}
All code
static void Main(string[] args)
{
GameMoves game = new GameMoves();
IEnumerator enumerator = game.Cross();
while (enumerator.MoveNext())
{
enumerator = (IEnumerator)enumerator.Current;
}
}
}
public class GameMoves
{
private IEnumerator cross;
private IEnumerator circle;
public GameMoves()
{
cross = Cross();
circle = Circle();
}
private int move = 0;
public IEnumerator Cross()
{
while (true)
{
Console.WriteLine("X, step {0}", move);
move++;
if (move > 9)
yield break;
yield return circle;
}
}
public IEnumerator Circle()
{
while (true)
{
Console.WriteLine("O, step {0}", move);
move++;
if (move > 9)
yield break;
yield return cross;
}
}
}
Solution
Both Cross
and Circle
are generators. They return a sequence of object
s by means of an IEnumerable
. That is, you could write:
foreach (var cross in Cross()) // works with Circle, also
{
// ...
}
And on every loop iteration, the next element to be returned is generated inside the Cross
or Circle
method. Those methods don't execute all at a time, instead each time a yield return
statement is reached, program execution will continue in the calling code (the foreach
loop), and the code inside the generator is only resumed when the next item is needed.
P.S.: Before my internet connection broke down for some hours, I had also wanted to comment on the strange fact that your generators keeps returning references to themselves via yield return
. That doesn't really make sense to me, to be honest; I've never seen that kind of code and I wonder if it actually does something useful?