Working through a tutorial (Professional ASP.NET MVC - Nerd Dinner), I came across this snippet of code:
public IEnumerable GetRuleViolation
1) Take this simpler example:
public void Enumerate()
{
foreach (var item in EnumerateItems())
{
Console.WriteLine(item);
}
}
public IEnumerable EnumerateItems()
{
yield return "item1";
yield return "item2";
yield break;
}
Each time you call MoveNext()
from the IEnumerator
the code returns from the yield
point and moves to the next executable line of code.
2) yield break;
will tell the IEnumerator
that there is nothing more to enumerate.
3) once per enumeration.
Using yield break;
public IEnumerable EnumerateUntilEmpty()
{
foreach (var name in nameList)
{
if (String.IsNullOrEmpty(name)) yield break;
yield return name;
}
}