Is there ever a reason to not use 'yield return' when returning an IEnumerable?

后端 未结 5 747
北海茫月
北海茫月 2020-12-09 16:16

Simple example - you have a method or a property that returns an IEnumerable and the caller is iterating over that in a foreach() loop. Should you always be using

5条回答
  •  渐次进展
    2020-12-09 16:42

    I don't think so. As @LBushkin suggests, if you were going to return something as a whole, you'd return an IList or whatever. If you're returning an IEnumerable, people expect deferred execution, so I think you should always use yield in that case.

提交回复
热议问题