‘yield’ Keyword in C#

Hi,

This post is mainly about the ‘yield’ keyword provided in C#. I never really got a chance to use this keyword until now. So thought I would just blog about it. This blog is not of my own writing; I would say it is rather 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 <expression>;
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<Product> 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<Product> GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;

        return products.ToList<Product>();
    }
}

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 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.

And above all, thanks to the author of that post that  helped me clearly understand the usage of the keyword.

Hope this helps!! 🙂

Advertisements

About Amogh Natu

Technology enthusiast, Associate Consultant @ Microsoft, music lover, love my guitar, Microsoft.NET, ASP.NET, C#.NET Professional.
This entry was posted in .NET, C#, CodeProject, General and tagged , , , , , , , . Bookmark the permalink.

2 Responses to ‘yield’ Keyword in C#

  1. Aw, this was an extremely good post. Taking a few minutes and actual effort to produce a really good article… but what can I say… I hesitate a lot and don’t manage to get anything done.

Your comments or opinions.....

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 )

Google+ photo

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

Connecting to %s