Search code examples
c#.netc#-2.0yield-return

yield return does not work in callee method


I'm new in C# and here is my code:

class Program {
    public static IEnumerable<string> enum2() {
        yield return "A";
        yield return "B";
    }

    public static IEnumerable<string> enum1() {
        enum2();
        yield return "C";
        enum2();
        yield return "C";
    }

    static void Main(string[] args) {
        foreach (string s in enum1()) {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }
}

Expected:

A
B
C
A
B
C

But Got:

C
C

The call trace is Main -> enum1() -> enum2() but why yield return does not work in enum2() ?


Solution

  • You're not doing anything with the results of enum2. You're creating the iterator but then never iterating the collection.

    Your code should look like:

    public static IEnumerable<string> enum1() 
    {
        foreach(var e in enum2())
            yield return e;
    
        yield return "C";
    
        foreach(var e in enum2())
            yield return e;
    
        yield return "C";
    }