Click here to Skip to main content
15,867,330 members
Articles / Programming Languages / C#

‘yield’ Keyword in C#

Rate me:
Please Sign up or sign in to vote.
4.82/5 (7 votes)
19 Feb 2014CPOL2 min read 38.5K   19   4
This post explains 'yield' keyword with examples.

Introduction

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:

C#
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

C#
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

C#
public static IEnumerable<Product> GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;

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

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionProject Link Broken Pin
Member 1023631819-Feb-14 12:25
Member 1023631819-Feb-14 12:25 
AnswerRe: Project Link Broken Pin
Amogh Natu19-Feb-14 20:08
professionalAmogh Natu19-Feb-14 20:08 
Thank you for pointing that out. I have uploaded the source code demo again and submitted it for review. It is yet to be approved. Kindly check after some time.

Thank you. Smile | :)
Thanks,
Amogh Natu.

AnswerRe: Project Link Broken Pin
Marco Bertschi19-Feb-14 23:29
protectorMarco Bertschi19-Feb-14 23:29 
AnswerRe: Project Link Broken Pin
Marco Bertschi19-Feb-14 23:26
protectorMarco Bertschi19-Feb-14 23:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.