1

Possible Duplicate:
In C#, why can't an anonymous method contain a yield statement?

I have this code:

Func<IEnumerable<int>> allNumbers = ()=> new []{1,2,3};
foreach (var number in allNumbers())
  Console.WriteLine(number);

But i would like (and has sense) to do somthing like this:

int i = 0;
Func<IEnumerable<int>> allNumbers = () => {yield return ++i;};
foreach (var number in allNumbers())
   Console.WriteLine(number);

and i get this compile error: "The yield statement cannot be used inside an anonymous method or lambda expression"

So why i can't use yield returns (lazy things) inside c# lambda expressions?

Community
  • 1
  • 1
Raúl Otaño
  • 4,640
  • 3
  • 31
  • 65

0 Answers0