Link copied to clipboard!
Iterator
Provide sequential access without exposing internals.
C#
// Custom enumerable producing integers [a..b]
class Range : IEnumerable
{
private readonly int _a, _b;
public Range(int a, int b) { _a = a; _b = b; }
public IEnumerator GetEnumerator()
{
for (int i = _a; i <= _b; i++)
yield return i;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
var sum = new Range(1, 5).Sum(); // 1+2+3+4+5 = 15
next