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;
}
}
}
Both
CrossandCircleare generators. They return a sequence ofobjects by means of anIEnumerable. That is, you could write:And on every loop iteration, the next element to be returned is generated inside the
CrossorCirclemethod. Those methods don’t execute all at a time, instead each time ayield returnstatement is reached, program execution will continue in the calling code (theforeachloop), 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?