Friday, 16 December 2011

Yield

The yield keyword is one of those things in C# that I thought was very complicated and difficult to understand. I grasped that it was used for creating iterators, but after looking at examples of it's usage I was still confused. Turns out there was something I was missing; when using yield return in a method who's return type is IEnumerable, C# automagically saves the state of the Enumerable, so repeated calls to the method will each return the next value in the Enumerable. With this in mind yield seems pretty straight forward. Reading around there are complexities in it's use, but to be honest I can't be bothered looking into it right now :-) 

I wrote this offensively simple program to prove to myself that I could write some code that used yield:


using System;
using System.Collections.Generic;

namespace Yield
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (int s in IntSequence())
            {
                Console.WriteLine(s); 
            }
            Console.ReadKey();
        }

        static IEnumerable<int> IntSequence()
        {
            for (int i = 0; i < 10; i++)
                yield return i;
           
            yield break;
        }

    }
}
  

Unsurprisingly it produces the following output:


No comments:

Post a comment