‘yield’ Keyword in C#

This post is mainly about the ‘yield' keyword provided in C#. This post is not totally of my own writing; Instead it is a re-blogging of a discussion about the keyword in this link.

‘yield‘ keyword is used in an Iterator block to provide a value to the enumerator object or to signal the end of an iteration. The syntax of yield statement is as follows:

yield return ;
yield break;

The following example clearly illustrates the proper usage of the keyword. The example shows two ways of returning an IEnumerable of “Product” entities.

Version-1: Using yield return
 
public static IEnumerable GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;
        foreach (Product product in products)
        {
            yield return product;
        }
    }
}

Version-2: returning the list

public static IEnumerable GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;
        return products.ToList();
    }
}

Usage and Advantage of yield keyword

The main usage of the yield keyword can be realized when we have to calculate the next value in the list or the next item in the list. In the second version shown above, when the return keyword is reached, the entire list is ready whereas in version-1, the entire list is not ready when the yield return statement is reached. Instead, for each occurrence of the yield return statement, the next item in the to-be-returned list is calculated.

One really good use of this type of functionality is that this helps spread the computational cost over a larger time frame. For example, if the list is hooked up to a GUI and the user never goes to the last page, you never calculate the final items in the list.

Another case where yield-return is preferable is if the IEnumerable represents an infinite set. Consider the list of Prime Numbers, or an infinite list of random numbers. You can never return the full IEnumerable at once, so you use yield-return to return the list incrementally.

In the above two versions, the one that is preferable is the version-2 as the product list is finite. So we can just calculate the complete list before itself.

I have uploaded a sample Demo program file (.CS file) showing the usage of yield.

Thanks to the author of the original post.

Hope this helps!!  
Next Recommended Reading Enumerators and Yield in C#