Yield Keyword Explained

The yield keyword is a neat, but infrequently used, language feature of c#. Essentially, it allows you to “queue-up” results to be returned by a method as an enumerable collection.

Consider this simple example that produces a collection of integers from 0 to 9:

static IEnumerable<int> GetValues()
{
    var result = new List<int>();
    for (var i = 0; i < 10; i++)
    {
        result.Add(i);
    }
    return result;
}

By using yield, we can skip the step of creating a List<int> variable to store our results. This function will produce the same result:

static IEnumerable<int> GetValuesYieldEdition()
{
    for (var i = 0; i < 10; i++)
    {
        yield return i;
    }
}
Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: