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
No you can't do that - an iterator block (something with a yield
) cannot use the regular (non-yield) return
. Instead, you need to use 2 methods:
public IEnumerable GetIntegers3()
{
if ( someCondition )
{
return new[] {4, 5, 6}; // compiler error
}
else
{
return GetIntegers3Deferred();
}
}
private IEnumerable GetIntegers3Deferred()
{
yield return 1;
yield return 2;
yield return 3;
}
or since in this specific case the code for both already exists in the other 2 methods:
public IEnumerable GetIntegers3()
{
return ( someCondition ) ? GetIntegers1() : GetIntegers2();
}