return
statement is used to return a value from a function.
If you have an iterator function like this:
public IEnumerable<int> IteratorOverInt() { }
a return statement in the above function would need to return a filled IEnumerable<int>
.
public IEnumerable<int> IteratorOverInt() {
return new List<int> { 1, 2, 3, 4 };
}
but if you are working on an iterator function, you will be using yield return
, so your code might look like this:
public IEnumerable<int> IteratorOverInt() {
for (int i = 0; i < 4; i++) {
yield return i;
}
}
So yield return
is returning an int
while the method signature demands IEnumerable<int>
What would a return
statement do in the above case? Return results overriding the yields? Concatenating whatever to the yields? return
doesn't make much sense in the above case.
Thus we need a way to return
that make sense in an iterator block, which is why there is yield break
.
Of course you can do it with a break
, but then how would you exit the function body if you have more code that'd execute? Wrap everything in a complicated if-else block? I'd say just having yield break
would be better.