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 ‘yield return’ in your IEnumerable method? Is there ever a reason not to? While I understand that it may not always be necessary to, or even “better” (maybe it’s a very small collection for example), is there ever a reason to actively avoid doing this?
The bit of code that got me thinking about this was a function I wrote very similar to the accepted answer in this thread – How do I loop through a date range?
Iterator blocks perform a “live” evaluation each time they are iterated.
Sometimes, however, the behavior you want is for the results to be a “snapshot” at a point in time. In these cases you probably don’t want to use
yield return, but instead return aList<>orSet, or some other persistent collection instead.It’s also unnecessary to use
yield returnif you’re dealing with query objects directly. This is often the case with LINQ queries – it’s better to just return theIEnumerable<>from the query rather than iterating andyield returning results yourself. For example: