Is yield useful outside of LINQ?

后端 未结 14 919
野性不改
野性不改 2020-12-24 06:44

When ever I think I can use the yield keyword, I take a step back and look at how it will impact my project. I always end up returning a collection instead of yeilding becau

14条回答
  •  独厮守ぢ
    2020-12-24 07:27

    I am a huge Yield fan in C#. This is especially true in large homegrown frameworks where often methods or properties return List that is a sub-set of another IEnumerable. The benefits that I see are:

    • the return value of a method that uses yield is immutable
    • you are only iterating over the list once
    • it a late or lazy execution variable, meaning the code to return the values are not executed until needed (though this can bite you if you dont know what your doing)
    • of the source list changes, you dont have to call to get another IEnumerable, you just iterate over IEnumeable again
    • many more

    One other HUGE benefit of yield is when your method potentially will return millions of values. So many that there is the potential of running out of memory just building the List before the method can even return it. With yield, the method can just create and return millions of values, and as long the caller also doesnt store every value. So its good for large scale data processing / aggregating operations

提交回复
热议问题