What does "yield break;" do in C#?


Question

I have seen this syntax in MSDN: yield break, but I don't know what it does. Does anyone know?

2
458
7/2/2016 12:09:44 AM

Accepted Answer

It specifies that an iterator has come to an end. You can think of yield break as a return statement which does not return a value.

For example, if you define a function as an iterator, the body of the function may look like this:

for (int i = 0; i < 5; i++)
{
    yield return i;
}

Console.Out.WriteLine("You will see me");

Note that after the loop has completed all its cycles, the last line gets executed and you will see the message in your console app.

Or like this with yield break:

int i = 0;
while (true)
{
    if (i < 5)
    {
        yield return i;
    }
    else
    {
        // note that i++ will not be executed after this
        yield break;
    }
    i++;
}

Console.Out.WriteLine("Won't see me");

In this case the last statement is never executed because we left the function early.

496
8/19/2016 12:34:33 PM

Exper Answer

The whole subject of iterator blocks is covered well in this free sample chapter from Jon Skeet's book C# in Depth.

11
9/1/2016 6:16:03 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon