Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

‘yield’ Keyword in C#

, 19 Feb 2014
Rate this:
Please Sign up or sign in to vote.
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:

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>();
    }
}

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)

Share

About the Author

Amogh Natu
Software Developer
India India
No Biography provided
Follow on   Twitter

Comments and Discussions

 
QuestionProject Link Broken PinmemberMember 1023631819-Feb-14 12:25 
AnswerRe: Project Link Broken PinprofessionalAmogh Natu19-Feb-14 20:08 
AnswerRe: Project Link Broken PinprotectorMarco Bertschi19-Feb-14 23:29 
AnswerRe: Project Link Broken PinprotectorMarco Bertschi19-Feb-14 23:26 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140926.1 | Last Updated 20 Feb 2014
Article Copyright 2013 by Amogh Natu
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid