October 2, 2024

C# iterator and yield

I first met up with this sort of thing in the ruby language where it is much more mainstream. The basic idea is that a method returns one value after another, in some magic way remembering where it left off. The magic of course is done by the compiler changing the semantics of a method call that contains a yield. The effect from the outside is very nice and fits right in to the "foreach" way of looping through a collection.

Here we use just static methods (i.e. "class" methods). The next step will be to create a class that implements an iterator that can be instantiated, allowing in theory any number of whatever iterator we set up to be running side by side.

using System;

namespace HogHeaven
{
    public class Iter
    {
        public static IEnumerable<int> Rat ()
        {
            yield return 34;
            yield return 99;
        }

        static int num1 = 1;
        static int num2 = 1;

		// Good old Fibonacci numbers
        public static IEnumerable<int> Fibo ()
        {
            int next_num;

            for ( ;; ) {
                yield return num1;
                next_num = num1 + num2;
                num1 = num2;
                num2 = next_num;
            }
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            int count = 0;

            foreach ( int x in Iter.Rat() )
                Console.WriteLine ( $"Value: {x}" );

            foreach ( int x in Iter.Fibo() ) {
                count++;
                Console.WriteLine ( $"Fibonacci {count}: {x}" );
                if ( count >= 30 )
                    return;
            }
        }
    }
}


Feedback? Questions? Drop me a line!

Tom's Computer Info / [email protected]