10

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;
}
oscilatingcretin
  • 10,457
  • 39
  • 119
  • 206
  • 3
    It would help if you add some code to clarify what you are trying to achieve. – René Vogt Oct 10 '16 at 13:24
  • 5
    What do you expect to happen after `yield continue`? What would the caller receive? Why not just go with `yield return 4;` after `2`? – BartoszKP Oct 10 '16 at 13:25
  • 1
    @BartoszKP That is *just an example*. I also tried just using continue within my method, but it doesn't build because it's not valid. – oscilatingcretin Oct 10 '16 at 13:28
  • 5
    @oscilatingcretin I know it's an example. I'm asking how do you expect this example to behave. It's unclear what do you need it for. Usually I would just write `yield return 1`, `yield return 2`, `yield return 4`. And the client would receive three integers, 1, 2, 4. What do you want to happen on the client-side between 2 and 4? – BartoszKP Oct 10 '16 at 13:29
  • 1
    @oscilatingcretin `continue` can be used within a loop **only**. – Ondrej Tucny Oct 10 '16 at 14:55
  • I'm hard pressed to imagine a problem a 2k+ user has with this. Do you want `foreach (int i in YieldTest()) Print(i)` to print `1 2 4`? But that's as simple as omitting the third line. _soconfused_ – Wolfzoon Oct 10 '16 at 16:20

2 Answers2

32

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;
    }
}
Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
1

If you want to pass the information about a hole in your data to the caller, then use nullable:

static IEnumerable<int?> YieldTest()
{
    yield return 1;
    yield return 2;
    yield return null;
    yield return 4;
}
BartoszKP
  • 34,786
  • 15
  • 102
  • 130