Search code examples
c#.netforeachiteratorunreachable-code

for each loop in an iterator method


Check out this program:

static class Program
{
  static void Main()
  {
    GetLinks();
    Console.WriteLine("Program failed!");
  }

  static IEnumerable<string> GetLinks()
  {
    throw new Exception();
    foreach (var item in new string[] { })
      yield return item;
  }
}

It's very weird but the result of this program is Program failed!, meaning the GetLinks function is not even called.
What's the explanation of this behavior?

Check it out for yourself.


Solution

  • Iterator blocks are lazy. You need to call it by invoking it in a foreach or something. Code inside your iterator block will execute only on the first call to MoveNext which foreach will do for you.

    As of now you're just preparing the query, you need to materialize it with the call to GetEnumerator followed by MoveNext.

    For example following code will fail as expected.

    static void Main()
    {
        foreach(var item in GetLinks())
            Console.WriteLine(item );
        Console.WriteLine("Program failed!");
    }
    

    Further reading Iterator block implementation details