Skip to content

How do you generate a "yield return null;" for an IEnumerator method? #897

Answered by ltrzesniewski
rickomax asked this question in Q&A
Discussion options

You must be logged in to vote

There is no direct IL equivalent to yield return. Methods that use yield are rewritten by the compiler as finite state machines, with state changes on yield statements.

I'm afraid this transformation is not exactly straightforward (especially starting from the low-level IL representation), but you can take a look at the Roslyn implementation if you'd like to replicate it. Comments there can be insightful, like this one:

//     yield return expression;
// is translated to
//     this.current = expression;
//     this.state = <next_state>;
//     return true;
//     <next_state_label>: ;
//     <hidden sequence point>
//     this.state = finalizeState;

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@rickomax
Comment options

Answer selected by rickomax
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants