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?
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>
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With