2

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?

nawfal
  • 70,104
  • 56
  • 326
  • 368
  • Can you provide more details? What yo want to do? Look at SelectMany Union. – gabba Feb 09 '13 at 21:25
  • I do have nothing to do. And certainly I can live with two blocks. Just trying to learn when I accidentally happened to code in one method and had to refactor to two methods to get compiled. Thats when I thought about it. – nawfal Feb 09 '13 at 21:27

2 Answers2

3

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.

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
1

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).

Servy
  • 202,030
  • 26
  • 332
  • 449
  • 2
    The difficulty is not just that it is a very tricky feature, but also that implementing it on top of the existing architecture would have been a lot of work. VB, which did not have iterators previously, just added iterator blocks and they added anonymous iterators while they were at it. I hope that with the improved Roslyn architecture the feature will be cheaper in a hypothetical future version of C#. – Eric Lippert Feb 10 '13 at 00:20
  • 1
    (And you'll note that in C# 5 we did add both async nominal methods and async lambdas.) – Eric Lippert Feb 10 '13 at 14:56