11

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.

13

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.

  • Wouldn't yield x; also of been a syntax error back then? – Moop Sep 26 '13 at 21:18
  • 1
    @Moop: By making it yield return, you don't even have to bother thinking about whether it was a syntax error or not. The chance of a collision becomes zero. – Robert Harvey Sep 26 '13 at 21:24
  • 2
    For "yield break;", it's essentially like "return;" in a void method, but using "return;" in combination with "yield return;" could be confusing. So the choice of "yield break" is a consequence of choosing "yield return". – Cyanfish Sep 26 '13 at 21:36
  • 3
    @Moop if you had a type named yield then yield x; would not be a syntax error, but a valid variable declaration. – Bojan Resnik Sep 27 '13 at 2:43
  • 1
    @moop: See also ericlippert.com/2009/05/11/reserved-and-contextual-keywords and blogs.msdn.com/b/ericlippert/archive/2010/09/27/… if the subject of introducing new keywords without breaking any code interests you. – Eric Lippert Sep 27 '13 at 22:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.