Search code examples
c#asp.net-mvcnerddinneryield-return

How does the NerdDinner example's Dinner.GetRuleViolations function return a list?


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.