I would avoid using yield return
if the method has a side effect that you expect on calling the method. This is due to the deferred execution that Pop Catalin mentions.
One side effect could be modifying the system, which could happen in a method like IEnumerable SetAllFoosToCompleteAndGetAllFoos()
, which breaks the single responsibility principle. That's pretty obvious (now...), but a not so obvious side effect could be setting a cached result or similar as an optimisation.
My rules of thumb (again, now...) are:
- Only use
yield
if the object being returned requires a bit of processing
- No side effects in the method if I need to use
yield
- If have to have side effects (and limiting that to caching etc), don't use
yield
and make sure the benefits of expanding the iteration outweigh the costs