HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
doeswhatbreakyield

Problem

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

Solution

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.

Code Snippets

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

Console.Out.WriteLine("You will see me");
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");

Context

Stack Overflow Q#231893, score: 651

Revisions (0)

No revisions yet.