In C# you can construct methods with the return type of IEnumerable<T>
and use yield return
and yield break
to control the flow. Here is a simple example that uses both controls:
public IEnumerable<int> GetEvens(int start, int end) {
if(end < start)
yield break;
if(start & 2 != 0)
start++;
for(int i = start; i <= end; i+=2) {
yield return i;
}
}
My question is, why was it originally designed to use two keywords with yield
and not use it like the following with the single yield
“yielding the return value”:
public IEnumerable<int> GetEvens(int start, int end) {
if(end < start)
return; // stop completely and return nothing
if(start & 2 != 0)
start++;
for(int i = start; i <= end; i+=2) {
yield i; // yield the current value.
}
}
To me, this is simpler to read and understand.
The slightly awkward yield return
syntax was created so that existing code that used the word “yield” as an identifier (variable name) would not break. (It makes perfect sense, for example, to have a variable named yield
if you’re working with financial code.) Since “yield return” would have been a syntax error back then, the new syntax would not break any existing code.
As for yield break
, no idea. That really doesn’t seem to have any good reason behind it that I can find.
8