Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yield in C# by infinite loop example

I am trying to understand how yield works in C#. For testing I made some example code:

using System;
using System.Text;

namespace ConsoleApplication1
{
    class GameFrame
    {
    };

    class GameState
    {
        public static GameFrame Begin()
        {
            Console.WriteLine("GameState.Begin");

            return new GameFrame();
        }

        public static GameFrame Play()
        {
            Console.WriteLine("GameState.Play");

            return new GameFrame();
        }

        public static System.Collections.Generic.IEnumerator<GameFrame> MainLoop()
        {
            yield return Begin();

            while (true)
            {
                yield return Play();
            }
        }
    };


    class Program
    {
        static void Main()
        {
            while (GameState.MainLoop() != null)
            {
            }
        }
    }
}

This code only tries to run once Begin function and call infinite times function Play. Please tell me why I never see my messages in console?

like image 824
Edward83 Avatar asked Dec 02 '25 08:12

Edward83


2 Answers

You need to enumerate the collection, You just check whether the result is null or not, that will not start the enumeration.

foreach (var frame in GameState.MainLoop())
{
    //Do whatever with frame
}

To make it work with `foreach you can make the MainLoop method return IEnumerable<GameFrame> instead of IEnumerator<GameFrame> Or just use

var enumerator = GameState.MainLoop();
while (enumerator.MoveNext())
{
     //Do whatever with enumerator.Current
}
like image 125
Sriram Sakthivel Avatar answered Dec 04 '25 23:12

Sriram Sakthivel


That's because you get back an IEnumerable<GameFrame>, but never actually iterate through it.

Try this instead:

var frames = GameState.MainLoop();
foreach(var frame in frames)
{
    // use the frame
    // e.g. frame.Show(); (note: in your example code, 
    // GameFrame doesn't have any members)
}
like image 21
Eren Ersönmez Avatar answered Dec 04 '25 23:12

Eren Ersönmez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!