Working through a tutorial (Professional ASP.NET MVC - Nerd Dinner), I came across this snippet of code:
public IEnumerable GetRuleViolation
A function that contains yield
commands is treated differently than a normal function. What is happening behind the scenes when that function is called, is that an anonymous type is constructed of the specific IEnumerable
type of the function, the function creates an object of that type and returns it. The anonymous class contains logic that executes the body of the function up until the next yield
command for every time the IEnumerable.MoveNext
is called. It is a bit misleading, the body of the function is not executed in one batch like a normal function, but rather in pieces, each piece executes when the enumerator moves one step forward.
With regards to your questions:
if
gets executed when you iterate to the next element.yield break
is indeed not necessary in the example above. What it does is it terminates the enumeration.