Prev | Current Page 304 | Next

Jon Skeet

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

I hope
you??™ll agree that this approach is very neat??”it expresses exactly what we want to do with
much less fuss about exactly how it should happen than you??™d have seen in a C# 1 version.
(It??™s even neater in C# 3, admittedly??¦7) It??™s relatively rare that you come across a situation
where you need to write to a captured variable, but again that can certainly have
its uses.
Still with me? Good. So far, we??™ve only used the delegate instance within the method
that creates it. That doesn??™t raise many questions about the lifetime of the captured variables
??”but what would happen if the delegate instance escaped into the big bad world?
How would it cope after the method that created it had finished?
5.5.4 The extended lifetime of captured variables
The simplest way of tackling this topic is to state a rule, give an example, and then
think about what would happen if the rule weren??™t in place. Here we go:
A captured variable lives for at least as long as any delegate instance
referring to it.
Don??™t worry if it doesn??™t make a lot of sense yet??”that??™s what the example is for. Listing
5.12 shows a method that returns a delegate instance. That delegate instance is created
using an anonymous method that captures an outer variable. So, what will happen
when the delegate is invoked after the method has returned?
static ThreadStart CreateDelegateInstance()
{
int counter = 5;
ThreadStart ret = delegate
{
Console.


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