Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yield return and "not all code paths return value"

Why the following code:

private static IEnumerable<int> TestYield(bool check)
{
    if (check)
    {
        return 1;
    }
    else
    {
        Console.WriteLine("In the else");
    }
}

produces an error with "not all code paths return value". However, the following code does not produce the same error:

private static IEnumerable<int> TestYield(bool check)
{
    if (check)
    {
        yield return 1;
    }
    else
    {
        Console.WriteLine("In the else");
    }
}

The only difference is the yield. What yield is making different that does not cause the same error?

like image 772
isaac.hazan Avatar asked Dec 02 '22 10:12

isaac.hazan


1 Answers

Any method body containing a yield break or a yield return statement is an iterator block. Within an iterator block, it's acceptable for execution to reach the closing brace of the method, as that's just equivalent to having a yield break - it's the end of the sequence.

In a regular method with a non-void return type, it's an error for the closing brace of a statement to be reachable. (Additionally, return 1; isn't a valid statement in a regular method with a return type of IEnumerable<int>.)

like image 107
Jon Skeet Avatar answered Dec 23 '22 00:12

Jon Skeet