After almost 4 years of experience, I haven't seen a code where yield keyword is used. Can somebody show me a practical usage (along explanation) of this keyword, and if so, aren't there other ways easier to fullfill what it can do?
Example of efficiency gained in a certain scenario
Not an iterator method, potential inefficient use of a big collection,
Iterator version, efficient
Simplify some programming scenarios
In another case, it makes some kinds of sorting and merging of lists easier to program because you just
Just one example is the merging of two lists:
This method yields back one contiguous list of items, effectively a merge with no intermediate collection needed.
To learn about how the iterators achieve their efficiency, the secret is in the IL code generated by the C# compiler. The IL generated for an iterator method differs drastically from that generated for a regular (non-iterator) method. This article (What Does the Yield Keyword Really Generate?) provides that kind of insight.
One of the usages for yield is when you want to return a collection from a method. Instead of writing something like this:
You can now make it smaller like:
This saves you the hassle of making some silly collection variable. Ofcourse this example isn't a reallife scenario.
When doing a search in the Orchard CMS source I stumbled across a nice real life example:
This is the most practical use I've used it for. I've used it myself a couple of times, but that's on my work machine and isn't booted up right now, so can't show you an example of myself.
It's a usefull keyword if you want to have cleaner/shorter code, but you can perfectly live without it.
A practical example may be found here:
There are a number of advantages of using yield over standard code:
However, as Jan_V said (just beat me to it by a few seconds :-) you can live without it because internally the compiler will produce code almost identical in both cases.
Here's an example:
The class performs date calculations based on a working week. I can tell an instance of the class that Bob works 9:30 to 17:30 every week day with an hour's break for lunch at 12:30. With this knowledge, the AscendingShifts() function will yield working shift objects between the supplied dates. To list all of Bob's working shifts between Jan 1 and Feb 1 this year, you'd use it like this:
The class doesn't really iterate over a collection. However, the shifts between two dates can be thought of as a collection. The
I have a small db data layer that has a
Basically the idea is to have typed CLR commands instead of manually filling
So there is a function that looks like this:
The class that inherits this
Then you can new up a
All in all makes it really easy to work with SQL commands and keep them typed.