C# — Yield

Yield is present in C# since 2.0, using a yield return construct similar to yield in Python.

Leon Maia ⌘
The Journal by Leon Maia

--

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.

--

--

Software Engineer at Zendesk. In the past worked helping to build the architecture of Globo’s video streaming platform. Visit my blog: https://leonmaia.me