C# — Yield
Yield is present in C# since 2.0, using a yield return construct similar to yield in Python.
Published in
1 min readOct 9, 2011
public object Solve()
{
return Fibonnaci().Where(i => i % 2 == 0).Sum();
}
private static IEnumerable<int> Fibonnaci()
{
int t1 = 1,
t2 = 2;
yield return t1;
yield return t2;
while (t2 < 4000000)
{
var aux = t2;
t2 += t1;
t1 = aux;
yield return t2;
}
}
With a yield return, the function automatically keeps its state during the iteration.