How can I put the current value of a variable into a delegate?

Liam McGillivray yoshi.pit.link.mario at gmail.com
Mon May 6 06:29:49 UTC 2024


Delegates can be a pain, as they often have results different 
from what one would intuitively expect. This can easily result in 
bugs.

Here's a line that caused a bug that took me awhile to find:
```
foreach(card; unitCards) card.submitted = delegate() => 
selectUnit(card.unit);
```

Each `UnitInfoCard` object (which `card` is a member of) contains 
a `Unit` object called `unit`. The intention of this line was 
that each object in `unitCards` would call `selectUnit` with it's 
own `unit` every time it calls `submitted`. Instead, every card 
calls `submitted` with the *last* value of `card`.

This is because the delegate assignment causes the local `card` 
variable to remain alive. The delegate that's assigned is linked 
to this variable itself, not the value at the time that the 
delegate is assigned.

Is there a way I can dereference a variable when placing it in a 
delegate, so that it's current value is used, rather than the 
variable itself?


More information about the Digitalmars-d-learn mailing list