public static IEnumerable<int> Foo()
{
}
The first has no return (hence the compiler message). Which makes sense - it doesn't have enough context to know what to do. Should it return null
? An empty enumerable? It can't know - so it won't let you compile.
public static IEnumerable<int> Foo()
{
if(false)
{
yield return 0;
}
}
The second does have a yield return
(even if unreachable), which gives it enough context to know that you want to return an enumerable (so it can set up the necessary state machine). Now, when the code executes you never actually hit that yield return
line (hence the compiler warning) - so what the caller will get is an empty enumerable.
This is expected -
If you don't have a yield break, the compiler would assume one at the
end of the function (just like a return; statement in a normal
function)
Given how ugly and un-intuitive the second code sample is, you may wish to instead use:
public static IEnumerable<int> Foo()
{
yield break;
}
Since it compiles, is clearer in its intent, and the compiler won't complain about unreachable code.