Does it do anything different than just returning from or letting the function complete to the end? Note VB.NET does not have yield break but requires that functions are marked with the iterator keyword.
Asked
Active
Viewed 777 times
0
-
see also http://stackoverflow.com/questions/231893/what-does-yield-break-do-in-c – Hans Kesting Nov 23 '12 at 06:30
-
No those example say what yield break does but it doesn't explain if there is any difference from just a simple return or letting the function exit naturally. – bradgonesurfing Nov 23 '12 at 07:07
1 Answers
3
Talking about C#
, If you want to write an iterator that returns nothing if the source is null or empty. Here is an example:
public IEnumerable<T> EnumerateThroughNull<T>(IEnumerable<T> source)
{
if (source == null)
yield break;
foreach (T item in source)
yield return item;
}
It becomes impossible to return an empty set inside an iterator without the yield break
. Also it specifies that an iterator has come to an end. You can think of yield break
as return statement which does not return value.
int i = 0;
while (true)
{
if (i < 5)
yield return i;
else
yield break; // note that i++ will not be executed after this statement
i++;
}

Furqan Safdar
- 16,260
- 13
- 59
- 93
-
1yield break ends the enumeration at that point, which in more complex enumerations which have complex internal state can be very useful. However, it is not required as for this use case as this answer implies. A simple if (source != null) { foreach ..... } would return an empty enumeration on null without yield break. – SAJ14SAJ Nov 23 '12 at 06:36
-
1The answer was edited while I was writing my first comment--the comment applies to the first example. The second is an example with more complex state where yield break helps with readability. However, again it is not impossible without it. Changing the yield break in the else statement of the second example to a simple break, to escape the loop, and get to the natural end of the function would also terminate the enumeration, for example. – SAJ14SAJ Nov 23 '12 at 06:39
-
1ok I think the answer is that it is not required. Letting a function complete naturally is also ok and is equivalent to yield break – bradgonesurfing Nov 23 '12 at 07:12
-
3"It becomes impossible to return an empty set inside an iterator without the `yield break`" is misleading - it is just *inconvenient* if you don't have `yield break`. But very possible. For example, in your first example you could just have `if(source != null) { foreach (T item in source) yield return item; } ` - and it is an iterator block yielding an empty sequence. – Marc Gravell Nov 23 '12 at 07:12