Question

I almost know its impossible and meaningless, but just trying to learn.. I have:

public IEnumerable<IEnumerable<object>> GetMany()
{
    while (someCondition)
        yield return GetFew();
}

static IEnumerable<object> GetFew()
{
    while (someOtherCondition)
        yield return new object();
}

Can I combine the two and form one method? Can two different iterator blocks lie in one method?

Edit: I am not asking how to solve the problem I have at hand. I'm trying to learn something new, so the larger question is "there a way two separate blocks can be made to work in one function"? I ask because there are anonymous types and closure in C# where you can have something new defined inside a method itself without a named type or method. Likewise for blocks?

Was it helpful?

Solution 2

What you're asking for is anonymous iterator blocks. Eric Lippert blogged on the subject a while back. In short, he said that it would be a wonderful feature that he'd love to see, but it's extraordinarily difficult to actually implement such a feature, so it has not been added to the language so far (and adding it in the future is unlikely).

OTHER TIPS

In short, no, you cannot have nested yield iterator within the same method.

yield is compiled at the method level. Every time you do yield return it will exit the method, and later continue where it left off. This means that if you nest yield statements, they will still be operating at a method level, not a block level.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top