Prev | Current Page 302 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

We then invoke x for the first time. It reads the value
of captured and prints it out??”our first line of output. It sets the value of captured to
???changed by x??? and returns. When the delegate instance returns, the ???normal???
method continues in the usual way. It prints out the current value of captured, giving
us our second line of output.
The normal method then changes the value of captured yet again (this time to
before second invocation) and invokes x for the second time. The current value of
captured is printed out, giving our last line of output. The delegate instance changes
captured to changed by x and returns, at which point the normal method has run out
of code and we??™re done.
That??™s a lot of detail about how a pretty short piece of code works, but there??™s really
only one crucial idea in it: the captured variable is the same one that the rest of the method
uses. For some people, that??™s hard to grasp; for others it comes naturally. Don??™t worry if
it??™s tricky to start with??”it??™ll get easier over time. Even if you??™ve understood everything
easily so far, you may be wondering why you??™d want to do any of this. It??™s about time we
had an example that was actually useful.
5.5.3 What??™s the point of captured variables?
To put it simply, captured variables get rid of the need for you to write extra classes
just to store the information a delegate needs to act on, beyond what it??™s passed as
parameters.


Pages:
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314