-1
using System.Reflection;

internal class TestReflection
{
    public static IEnumerable<object> ParseType(Type t)
    {
        foreach (MemberInfo mi in t.GetMembers())
        {
            yield return mi;
            foreach (object x in mi.GetCustomAttributes(true))
            {
                yield return x;
            }
        }
    }
}

So my question is how does the iterator know when to step into the nested foreach. I had assumed that the first yield return would always execute and the nested yield return is never executed. But this is not the case, which indicates there's something I don't quite understand about the yield return statement.

Can someone explain this?

Thanks James

James Z.
  • 119
  • 2
  • 9
  • This might shread **some** light for you (or not, probably not the best explanation): http://blog.alxandr.me/2012/10/10/yielding-results-the-process-involved-with-generating-generators/ – Alxandr Jun 04 '13 at 15:41

1 Answers1

0

If only a single element is requested from the enumerator, then you'd be right, but if more elements are requested, then the inner foreach must execute to produce more elements.

recursive
  • 83,943
  • 34
  • 151
  • 241