Sobes.tech
Junior — Senior

Analysis of iterator behavior with yield operator in C#

livecode

Task condition

Determine what output the program will produce when executing the following code.

var start = 0;
var iterator = GenerateSequence(start);

static IEnumerator<int> GenerateSequence(int start)
{
    if (start % 2 != 0)
    {
        yield break;
    }

    if (start < 3)
    {
        start++;
        yield return start;
    }
}

iterator.MoveNext();
iterator.MoveNext();
iterator.MoveNext();
Console.WriteLine(iterator.Current);