Simple Usage
suggest changeThe yield keyword is used to define a function which returns an IEnumerable or IEnumerator (as well as their derived generic variants) whose values are generated lazily as a caller iterates over the returned collection. Read more about the purpose in the remarks section.
The following example has a yield return statement that’s inside a for loop.
public static IEnumerable<int> Count(int start, int count)
{
for (int i = 0; i <= count; i++)
{
yield return start + i;
}
}
Then you can call it:
foreach (int value in Count(start: 4, count: 10))
{
Console.WriteLine(value);
}
Console Output
4
5
6
...
14
The foreach creates the iterator once. Each iteration resumes that same iterator at the next yield return, which occurs during the next iteration of the for loop. Because the condition is i <= count, Count(4, 10) yields 11 values, 4 through 14.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents