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;
}
{
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.)
Guvf vf cebonoyl abg jung lbh ner trggvat ng, ohg vs n lvryq oernx jnf gur bayl fgngrzrag va gur zrgubq gura erzbivat vg jbhyq boivbhfyl oernx gur pbqr.
LikeLike
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.
LikeLike
Jura gurer vf ab “lvryq erghea” be “erghea” fgngrzrag naljurer va gur shapgvba.
LikeLike
na rnfl bar jbhyq or n erphefvir shapgvba
fgngvp VRahzrenoyr grfg(vag qhzzl) { vs (qhzzl > 0) grfg(qhzzl – 1); lvryq oernx;}
LikeLike
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;
}
LikeLike
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.
LikeLike
Thanks Jon,
I realized about it just after I posted the reply. :( Nonetheless, I learnt something new today.
Thanks to James & Jay
LikeLike
Sorry, Thanks to Justin & Jay.
LikeLike
No need to apologise, Kalpesh – it’s just a bit of fun, and it’s interesting to see people’s thought processes.
LikeLike
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?
LikeLike
@Erik: You’re absolutely right, it would break it completely.
LikeLike