I have a vague understanding of the yield
keyword in c#, but I haven\'t yet seen the need to use it in my code. This probably comes from a lack of understanding of
Yield is used in enumerators. The C# compiler automatically pauses execution of your enumeration loop and returns the current value to the caller.
IEnumerable GetIntegers(int max) {
for(int i = 1; i <= max) {
yield return i; // Return current value to the caller
}
}
-- or (more clunky) --
IEnumerable GetIntegers(int max) {
int count = 0;
while(true) {
if(count >= max) yield break; // Terminate enumeration
count++;
yield return count; // Return current value to the caller
}
}
More details on MSDN.