Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yield continue? [closed]

OP edit: This was a bad question predicated upon a misunderstanding of how yield return works. The short answer: If you don't want to yield return something, don't yield return anything.


There's yield return to return the next element in the collection and then there's yield break to end the iteration. Is there a sort of yield continue to tell the loop controller to skip to the next element?

Here's what I am trying to achieve, though it obviously doesn't build:

static IEnumerable<int> YieldTest()
{
    yield return 1;
    yield return 2;
    yield continue;
    yield return 4;
}
like image 420
oscilatingcretin Avatar asked Oct 10 '16 13:10

oscilatingcretin


People also ask

Does yield mean break?

yield verb (BEND/BREAK)to bend or break under pressure: His legs began to yield under the sheer weight of his body.

Is yield break the same as return?

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.

Does yield break return null?

1. "yield break" breaks the Coroutine (it's similar as "return"). "yield return null" means that Unity will wait the next frame to finish the current scope. "yield return new" is similar to "yield return null" but this is used to call another coroutine.

Does yield stop for loop Python?

'yield statement' won't terminate the function during the function call. During multiple calls, it will generate successive output.


1 Answers

There is no need to have a separate yield continue statement. Just use continue or any other conditional statement to skip the element as you need within your enumeration algorithm.

The enumeration algorithm that uses yield is internally transformed into a state machine by the compiler, which can the be invoked several times. The point of yield is that it generates an output, effectively pausing / stopping the state machine at the place where it's used. The effect of a possible yield continue would be none at all in respect to the behavior of the state machine. Hence it is not needed.

Example:

static IEnumerable<int> YieldTest()
{
    for (int value = 1; value <= 4; value++)
    {
        if (value == 3) continue;  // alternatively use if (value != 3) { … }
        yield return value;
    }
}
like image 141
Ondrej Tucny Avatar answered Sep 18 '22 14:09

Ondrej Tucny