The yield statement cannot be used inside an anonymous method or lambda expression

I thought I was being pretty cool with this code:

IEnumerator System.Collections.Generic.IEnumerable.GetEnumerator( ) {
  Action<UnbalancedBinaryTree> yielder = null;
  yielder = t => {
    yielder(t.Left);
    if (!t.IsEmpty)
      yield return t.Value;
    yielder(t.Right);
  };
  yielder(this);
}

But as it turns out (and I think I knew before, but had forgotten), C# doesn’t accept this. Not in 3.0 at least, and I think not in 4.0 either. Need to test. Meanwhile — why? Hm…

3 Comments on The yield statement cannot be used inside an anonymous method or lambda expression

  1. Yep, no love for that in 4 either. Maybe vNext (fingers crossed)…

    Like

  2. Igor Dontsov // March 9, 2010 at 10:16 pm // Reply

    Check this post by Eric Lippert: “Iterator Blocks Part Seven: Why no anonymous iterators?” http://blogs.msdn.com/ericlippert/archive/2009/08/24/iterator-blocks-part-seven-why-no-anonymous-iterators.aspx

    Like

  3. Hey Igor,

    Thanks for the link. Yeah… sounds a bit like “we don’t really think it’s quite that useful and we’re scared of getting it wrong” 🙂 Legitimate reasons I guess, but still a pity.

    Like

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s