What is the yield keyword used for in C#?

后端 未结 17 2027
盖世英雄少女心
盖世英雄少女心 2020-11-22 05:26

In the How Can I Expose Only a Fragment of IList<> question one of the answers had the following code snippet:

IEnumerable FilteredList()
{
         


        
      
      
      
17条回答
  •  故里飘歌
    2020-11-22 05:48

    One major point about Yield keyword is Lazy Execution. Now what I mean by Lazy Execution is to execute when needed. A better way to put it is by giving an example

    Example: Not using Yield i.e. No Lazy Execution.

    public static IEnumerable CreateCollectionWithList()
    {
        var list =  new List();
        list.Add(10);
        list.Add(0);
        list.Add(1);
        list.Add(2);
        list.Add(20);
    
        return list;
    }
    

    Example: using Yield i.e. Lazy Execution.

    public static IEnumerable CreateCollectionWithYield()
    {
        yield return 10;
        for (int i = 0; i < 3; i++) 
        {
            yield return i;
        }
    
        yield return 20;
    }
    

    Now when I call both methods.

    var listItems = CreateCollectionWithList();
    var yieldedItems = CreateCollectionWithYield();
    

    you will notice listItems will have a 5 items inside it (hover your mouse on listItems while debugging). Whereas yieldItems will just have a reference to the method and not the items. That means it has not executed the process of getting items inside the method. A very efficient a way of getting data only when needed. Actual implementation of yield can seen in ORM like Entity Framework and NHibernate etc.

提交回复
热议问题