Why can\'t we use both return and yield return in the same method?
For example, we can have GetIntegers1 and GetIntegers2 below, but not GetIntegers3.
pu
The compiler re-writes any methods with a yield
statement (return or break). It currently cannot handle methods that may or may not yield
.
I'd recommend having a read of chapter 6 of Jon Skeet's C# in Depth, of which chapter 6 is available for free - it covers iterator blocks quite nicely.
I see no reason why this would not be possible in future versions of the c# compiler however. Other .Net languages do support something similar in the form of a 'yield from' operator (See F# yield!). If such an operator existed in c# it would allow you to write your code in the form:
public IEnumerable GetIntegers()
{
if ( someCondition )
{
yield! return new[] {4, 5, 6};
}
else
{
yield return 1;
yield return 2;
yield return 3;
}
}