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)
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.