7

Possible Duplicate:
yield statement implementation

I've seen msdn docs and it says:

The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block. In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object.

So it means yield keyword is a Syntactic sugar and compiler does the heavy work of generating the Iterator. (Am I Correct ?)

Then what is the generated implementation code for this syntactic sugar.

Community
  • 1
  • 1
Shekhar_Pro
  • 18,056
  • 9
  • 55
  • 79
  • 3
    99% of a programming language is syntactic sugar. After all there is the concept of Turning Completeness and there is a language with a single instruction that has been proven to be Turing complete. In a programming language it's all about the syntax. – Stilgar Nov 27 '11 at 12:59
  • @Stilgar +1 ha ha nice comment :) tough not sure about its correctness. – Shekhar_Pro Nov 27 '11 at 13:01
  • Just for the records: Syntactic suger is a Good Thing™. – JensG Mar 29 '14 at 12:23

1 Answers1

5

The generated code depends on the original, but generally speaking a state machine gets generated which keeps track of the current state of the collection.

See yield statement implementation, this answer by Eric Lippert and this blog post by Jon Skeet.

Community
  • 1
  • 1
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • thanx.. and +1 for that link to Jon skeet's post – Shekhar_Pro Nov 27 '11 at 12:58
  • 1
    See also Raymond's series of articles on the subject: http://blogs.msdn.com/b/oldnewthing/archive/2008/08/12/8849519.aspx – Eric Lippert Nov 27 '11 at 15:03
  • @EricLippert Thanx for the link to that excellent article :) – Shekhar_Pro Nov 28 '11 at 12:27
  • Just a quick question ... why can't iterators be implemented using some kind of stack pointer instead? If b is a local variable inside a function a(), and a calls into b to iterate, then b yielding can simply jump to a's code and just move the stack pointer back to what it was when a() first started. If a() pushes more stuff onto the stack, it goes above b's stuff. Each function has to declare variables upfront and keep a pointer to its stack, but when a() exits, it can just pop everything. Why not? – Gregory Magarshak May 22 '17 at 03:27