Yield return
I saw this code and got a little confused:
What is the reasoning behind yield return in this case? Im thinking a normal return would break the foreach and that there are no need for using yield.
When googling i found that the yield can be useful to reduce code(look at attached image for example) but i cant see how it is contributing to that in the case mentined above.
Thanks in advance 🙂
3 Replies
yield return is used to lazily return a collection, whereas regular return would just return the first item from that collection in that above code sample (if you kept everything else in the code the same)
If you wanted to return the entire collection using a regular return instead of yield return, you'd probably do something like
return courses.Select(entity => EntityToModel.CreateCourseFromEntity(entity));
(which internally does basically the same thing as in your first message)Ah okey then i understand! Thank you 🙂
That command had an error
UnknownCommand: Unknown command.
Remove your reaction to delete this message