first_page the funky knowledge base
personal notes from way, _way_ back and maybe today

.NET 3.0/3.5: Flippant Remarks about the yield Keyword

The yield keyword is used only inside of a for loop and with an IEnumerable<> generic type to form a pattern like this:

class Program
{
    static void Main(string[] args)
    {
        IEnumerable&lt;int&gt; integers = Program.YieldList( 1, 10, 2 );
    }

    public static IEnumerable&lt;int&gt; YieldList( int start,
        int end, int increment )
    {
        for (int current = start;
            current &lt;= end; current += increment)
        {
            yield return current;
        }
    }
}

The variable current is the same type as that specified in IEnumerable<int> and the yield keyword fills IEnumerable<int> until the loop is finished. Without yield, the loop would return after one pass (actually the code won’t compile!).

For more information, see:

“yield (C# Reference)”
http://msdn2.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx

“Drop the temporary lists and leverage yield”
http://www.jpboodhoo.com/blog/
    DropTheTemporaryListsAndLeverageYield.aspx

As elegant as this pattern appears, note that, as of this writing, setting a breakpoint inside of YieldList() and getting the Debugger to stop on it is “problematic” (just not possible). Targeting .NET 3.5 from Visual Studio 2008 provides a debugging visualizer for IEnumerable<>.

mod date: 2007-12-19T05:50:43.000Z