Prev | Current Page 312 | Next

Jon Skeet

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


They make good logical sense (and any change to make them simpler would probably
either make them less useful or less logical), but they make it quite easy to produce
horribly complicated code.
Don??™t let that discourage you from using them sensibly, though??”they can save you
masses of tedious code, and when they??™re used appropriately they can be the most
readable way of getting the job done. But what counts as ???sensible????
159 Capturing variables in anonymous methods
GUIDELINES FOR USING CAPTURED VARIABLES
The following is a list of suggestions for using captured variables:
?–  If code that doesn??™t use captured variables is just as simple as code that does,
don??™t use them.
?–  Before capturing a variable declared by a for or foreach statement, consider
whether your delegate is going to live beyond the loop iteration, and whether
you want it to see the subsequent values of that variable. If not, create another
variable inside the loop that just copies the value you do want.
?–  If you create multiple delegate instances (whether in a loop or explicitly) that
capture variables, put thought into whether you want them to capture the same
variable.
?–  If you capture a variable that doesn??™t actually change (either in the anonymous
method or the enclosing method body), then you don??™t need to worry as much.
?–  If the delegate instances you create never ???escape??? from the method??”in other
words, they??™re never stored anywhere else, or returned, or used for starting
threads??”life is a lot simpler.


Pages:
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324