Trivia: when is a no-op not a no-op?

Hopefully most readers are familiar with the yield break; statement. Usually, if it appears at the end of a method its a no-op which can be removed with no change in behaviour. For instance:

public IEnumerable<int> Range1 (int start, int count)
{
    for (int i=0; i < count; i++)
    {
         yield return start+i;
    }
    yield break;
}

public IEnumerable<int> Range2 (int start, int count)
{
    for (int i=0; i < count; i++)
    {
         yield return start+i;
    }
}

Can anyone think of a situation where a yield break; directly before the closing brace of a method cannot be removed without breaking the code? (I suggest that early answers are given in ROT-13 to avoid spoiling it for anyone else.)

11 thoughts on “Trivia: when is a no-op not a no-op?”

  1. Nsgre fhozvggvat zl ynfg pbzzrag V ernyvmrq gung V cebonoyl fubhyq unir pynevsvrq n yvggyr ovg. Vs lbh unir n zrgubq gung ergheaf na rahzrengbe jvgu n fvatyr fgngrzrag bs “lvryq oernx;” va vg, gura gur “lvryq oernx;” vf tbvat gb cebqhpr VY gb trarengr na rzcgl rahzrengbe naq gurersber vf abg n ab-bc.

    Like

  2. N fgngrzrag gung jvyy pnhfr gur ybbc gb oernx (abg lvryq oernx)
    sbe r.t.

    choyvp fgngvp VRahzrenoyr Enatr2 (vag fgneg, vag pbhag)
    {
    sbe (vag v=0; v < pbhag; v++)
    {
    vs (v == 5) oernx;
    lvryq erghea fgneg+v;
    }
    Pbafbyr.JevgrYvar("oernxvat");
    lvryq oernx;
    }

    Like

  3. Justin, Jay: spot on

    Eber: your example is correct, but the emphasis in the explanation is a little off

    Kalpesh: not quite – removing the “yield break” at the end here wouldn’t change anything.

    Like

  4. Sorry to open up an old thread, but am I incredibly stupid when I think that removing the yield break statement in Justin’s example would always make the code uncompilable?

    Like

Leave a comment