Simple Usage

suggest change

The 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

Live Demo on .NET Fiddle

Each iteration of the foreach statement body creates a call to the Count iterator function. Each call to the iterator function proceeds to the next execution of the yield return statement, which occurs during the next iteration of the for loop.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Yield Keyword:
* Simple Usage

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
117 Yield Keyword
127 Caching
135 Pointers
147 C# Script