iterate a yield return in csharp

To iterate a yield return in C#, we need to use an iterator block, which generates an enumerator that can be iterated over using a foreach loop or other enumeration techniques.

Here's an example:

main.cs
public static IEnumerable<int> GetNumbers()
{
    yield return 1;
    yield return 2;
    yield return 3;
}

// Usage:
foreach(var number in GetNumbers())
{
    Console.WriteLine(number);
}
// Output: 1, 2, 3
209 chars
14 lines

In the above example, GetNumbers() method returns an IEnumerable<int> object, which internally uses the yield return statement to generate a sequence of integers.

The foreach loop iterates over the sequence by calling the enumerator's MoveNext() method and fetching the current element from the Current property.

The yield return statement pauses the execution of the method and returns the current value to the caller. Then, when the next value is requested (usually by calling MoveNext() on the iterator), the method resumes execution from where it left off and generates the next value.

This allows us to lazily generate a sequence of values on-demand, without having to generate all of them up-front.

gistlibby LogSnag