Another day in office, and you are writing your code, you need to call a function which is going to create a list of objects then it's going to populate the list and return it back to your main function. Sounds familiar right? Probably, your code might look like this if you are not using yield.
I am sure your awesome object is better that this one, and probably it comes from database. Do you see any problem in this example. It works just fine! But if you like to write less code and if you don't want to create the temp objects in repository functions which hold the object for a second and got destroyed by garbage collector, you may want to use yield. Let's see how this example is going to look like if we use yield.
You can find/run this code in my .Net fiddle account.
As you can see, we got rid off the temp object which holds the list of our objects. This should help to the garbage collector since we are not creating a list to hold our data. Application calls the Load function for each item, and it remembers each time which item was the current and which item is the next without a List object. You can use yield break if you like to break and not continue the loop.
Also I used IEnumerable rather List because yield is tied to it. Yield makes your collection Lazy. If you want to get first three awesome objects, you can pass a filtering method and load function will stop when it reaches fourth item. I tried to explain yield without going in technical details here, If you like read about the yield more, here is a documentation from Microsoft.

No comments:
Post a Comment