Is 'yield' keyword a syntactic sugar ? What is its Implementation [duplicate]
Asked Answered
W

1

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.

Wringer answered 27/11, 2011 at 12:23 Comment(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.Eastbound
@Eastbound +1 ha ha nice comment :) tough not sure about its correctness.Wringer
Just for the records: Syntactic suger is a Good Thing™.Alceste
W
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.

Whelk answered 27/11, 2011 at 12:26 Comment(4)
thanx.. and +1 for that link to Jon skeet's postWringer
See also Raymond's series of articles on the subject: blogs.msdn.com/b/oldnewthing/archive/2008/08/12/8849519.aspxStalemate
@EricLippert Thanx for the link to that excellent article :)Wringer
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?Pavid

© 2022 - 2024 — McMap. All rights reserved.