C# Feature – Iterator (yield)
Overview
Section titled “Overview”Iterators let you write lazy sequences using yield return
and yield break
.
Introduced In
Section titled “Introduced In”C# 2 (2005)
Before
Section titled “Before”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;}
Gotchas & Best Practices
Section titled “Gotchas & Best Practices”- Deferred execution; exceptions surface on enumeration.
- Can’t mix yield with ref/out parameters or unsafe blocks in the same method.