yield block

  • Thread starter Thread starter puzzlecracker
  • Start date Start date
P

puzzlecracker

"Any parameters passed to the method containing the yield block are
added as public fields to the generated enumerator class"

Why does compiler adds these parameters as public fields?


please explain the need for that.

Thanks
 
Think how the iterator block must actually work... it isn't a
regular .NET method - the compiler actually strips it down into
pieces, and each time MoveNext() is called it runs the next segment of
your code. In the time between MoveNext() calls, it needs to store all
the data somewhere (they can't live on the stack if the method has
exited), so it uses fields.

You might want to look at the (free) chapter 6 from Jon Skeet's C# in
Depth, which explains all.

Marc
 
Marc said:
Think how the iterator block must actually work... it isn't a
regular .NET method - the compiler actually strips it down into
pieces, and each time MoveNext() is called it runs the next segment of
your code. In the time between MoveNext() calls, it needs to store all
the data somewhere (they can't live on the stack if the method has
exited), so it uses fields.

I suspect the question is why these fields would be public.
 
"Any parameters passed to the method containing the yield block are
added as public fields to the generated enumerator class"

Why does compiler  adds these parameters as public fields?

please explain the need for that.

It was easier to implement the compiler that way. It allowed them to
reuse some other code (from anonymous methods, I believe). Yes, it
would be a bit cleaner to pass the values into a constructor for the
generator class, but as this is all generated code which can't be
referred to at compile-time, I'm willing to give them a bit of
leeway :)

Jon
 
I suspect the question is why these fields would be public.

Ahh - if the emphasis is on the word "public", then I'd agree. In
fact, Jon and I had a discussion on this earlier in the week;
"private", or at least "internal" would seem more likely - but you'd
need reflection to abuse them, and with reflection (and enough trust)
all bets are off anyway...

Marc
 
Back
Top