c# - Why can't "return" and "yield return" be used in the same method? -
why can't use both return , yield return in same method?
for example, can have getintegers1 , getintegers2 below, 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; } }
return
eager. returns entire resultset @ once. yield return
builds enumerator. behind scenes c# compiler emits necessary class enumerator when use yield return
. compiler doesn't runtime conditions such if ( somecondition )
when determining whether should emit code enumerable or have method returns simple array. detects in method using both not possible cannot emit code enumerator , @ same time have method return normal array , same method.
Comments
Post a Comment