Prev | Current Page 313 | Next

Jon Skeet

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


?–  Consider the extended lifetime of any captured variables in terms of garbage
collection. This is normally not an issue, but if you capture an object that is
expensive in terms of memory, it may be significant.
The first point is the golden rule. Simplicity is a good thing??”so any time the use of a
captured variable makes your code simpler (after you??™ve factored in the additional
inherent complexity of forcing your code??™s maintainers to understand what the captured
variable does), use it. You need to include that extra complexity in your considerations,
that??™s all??”don??™t just go for minimal line count.
We??™ve covered a lot of ground in this section, and I??™m aware that it can be hard to
take in. I??™ve listed the most important things to remember next, so that if you need to
come back to this section another time you can jog your memory without having to
read through the whole thing again:
?–  The variable is captured??”not its value at the point of delegate instance creation.
?–  Captured variables have lifetimes extended to at least that of the capturing delegate.
?–  Multiple delegates can capture the same variable??¦
?–  ??¦but within loops, the same variable declaration can effectively refer to different
variable ???instances.???
?–  for/foreach loop declarations create variables that live for the duration of the
loop??”they??™re not instantiated on each iteration.


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