yield return hands back a value. yield break says there are no more values and ends the
sequence — it is the return; of an iterator.
C#
static IEnumerable<string> ReadUntilBlank(string[] lines)
{
foreach (var line in lines)
{
if (string.IsNullOrWhiteSpace(line))
{
yield break;
}
yield return line.Trim();
}
}
Falling off the end of the method does the same thing, so yield break earns its place only when
you want to stop from inside a branch.
You can also yield from several places. There is no rule that an iterator has one yield return:
C#
static IEnumerable<string> Envelope(string body)
{
yield return "--- begin ---";
yield return body;
yield return "--- end ---";
}
Do not reach for plain return
yield return is not a return. A return with a value is illegal in an iterator — the method
already declared what it produces by yielding. Write yield break when you mean "stop".
Try it: Task 2
Open the editor