Skip to content

C# Feature – Iterator (yield)

Iterators let you write lazy sequences using yield return and yield break.

C# 2 (2005)

public IEnumerable<int> Evens(int max)
{
var list = new List<int>();
for (int i=0; i<=max; i++) if (i%2==0) list.Add(i);
return list;
}
public IEnumerable<int> Evens(int max)
{
for (int i=0; i<=max; i++)
if (i%2==0) yield return i;
}
  • Deferred execution; exceptions surface on enumeration.
  • Can’t mix yield with ref/out parameters or unsafe blocks in the same method.