How does the NerdDinner example's Dinner.GetRuleViolations function return a list?
-
05-07-2019 - |
Question
From what I've read,
yield return <value>
jumps out of the function the moment the line is executed. However, Scott Guthrie's text indicates that
var errors = dinner.GetRuleViolations();
successfully pulls out a list of all the rule violations even though GetRuleViolations is a long list of
if(String.someFunction(text))
yield return new RuleViolation("Scary message");
if(String.anotherFunction(text))
yield return new RuleViolation("Another scary message");
How does this work?
Solution
It doesn't return a list. It returns an IEnumerable<RuleViolation>
. yield return
returns a value in an iterator method. An iterator is an easy way to generate a sequence of elements in a method.
OTHER TIPS
The yield keyword uses what's known as lazy evaluation. What this means practically is that anything following a "yield return" will not be evaluated until it is requested from the enumerator.
Also have a look at Eric Lippert's blog on Iterator Blocks.
Part 1
Part 2 - Why No Ref or Out Parameters
Part 3 - Why No yield in finally
Part 4 - Why No yield in catch
Part 5 - Push vs Pull
Part 6 - Why no unsafe code
It works because yield return
returns a value to an enumerator object, basically automating some plumbing code for you (i.e. it's syntactic sugar). It doesn't cause the method to return, that would be yield break
.
More information: