Menu

How a yield return iterator decompiles
📰

How a yield return iterator decompiles

DEV Community: csharp·Zero Heartbeat·6 days ago
#QYMP1q8E
#devtocsharp#devto#dev#1__state#return
Long article (2087 words) — no AI summary yet.
Reading 0:00
15s threshold

Write a three-line method that returns IEnumerable<int> and uses yield return , compile it, and open the assembly. Your method is gone. In its place sits a compiler-generated class with a name like <Window>d__0 , half a dozen fields whose names begin with <> , and a MoveNext() that is one flat switch over an integer. The loop you wrote has been turned inside out. Rebuilding your yield return from that switch is a decompiler's job, and it is a good example of how much machinery one keyword hides.

The real question

yield return makes a method resumable . It returns a value, freezes every local, and continues from the next statement when the consumer pulls again. A normal method cannot do that — its stack frame is gone the moment it returns.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.