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.
public IEnumerable<int> GetIntegers1()
{
return new[] { 4, 5, 6 };
}
public IEnumerable<int> GetIntegers2()
{
yield return 1;
yield return 2;
yield return 3;
}
public IEnumerable<int> GetIntegers3()
{
if ( someCondition )
{
return new[] {4, 5, 6}; // compiler error
}
else
{
yield return 1;
yield return 2;
yield return 3;
}
}
returnis eager. It returns the entire resultset at once.yield returnbuilds an enumerator. Behind the scenes the C# compiler emits the necessary class for the enumerator when you useyield return. The compiler doesn’t look for runtime conditions such asif ( someCondition )when determining whether it should emit the code for an enumerable or have a method that returns a simple array. It detects that in your method you are using both which is not possible as he cannot emit the code for an enumerator and at the same time have the method return a normal array and all this for the same method.