yield block

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
 
M

Marc Gravell

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
 
B

Ben Voigt [C++ MVP]

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.
 
J

Jon Skeet [C# MVP]

"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
 
M

Marc Gravell

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top