Friday, April 11, 2008

Yield Keyword

You use yield to return values many times from one method call. The test below shows how this can be done: (Notice the first line uses a Collection Initializer)
private List<string> Names = new List<string>() { "Mark", "Matt" };

[Test]
public void RunLoopWithYield()
{
    string output = string.Empty;

    foreach (string yieldedValue in ReturnOneNameAtATime())
    {
        output += yieldedValue;
    }

    Assert.AreEqual("Start_Mark_Matt_End", output);
}

private IEnumerable<string> ReturnOneNameAtATime()
{
    // Return this first and then come back.
    yield return "Start_";

    foreach (string name in Names)
    {
        // Return one name at a time.
        yield return name + "_";
    }

    // Return this last but come back one last time
    // to actually exit method.
    yield return "End";
}
See how the path of execution is different with the yield statements: