tags:

views:

110

answers:

2

I've heard that if lambda expressions are used to subscribe to an event, then this creates a weak reference to the event handler code, so it is not required to explicitly unsubscribe from the event when the subscriber dies/is no longer interested. Is this true? E.g.

aPersion.PropertyChanged += (s, e) =>
                    {
                        if (e.PropertyName == "Name")
                        {
                            this.Name = this.TheController.Name;
                        }
                    };
+2  A: 

No, in the context of event subscriptions lambda expressions are just delegates for all intents and purposes and hence remain prone to Lapsed Listener issues. So no, it's definitely not a weak reference.

There are a variety of approaches for using weak references to work around this issue, which are summarised well in this post from Damien Guard

Ruben Bartelink
Thanks very much Ruben - seems WeakEventManager is my new friend in my situation.
drjeks
+2  A: 

No, this is myth. Lambdas create regular delegates (in this usage, at least). The confusion is often simply that if the publishing object is going to be finished with before or at around the same time as the subscriber, then there is no need to unsubscribe. The event delegate only keeps the subscriber aliver, not the publisher.

In the example given, therefore, it depends on whether your publisher: aPersion (presumably a person or similar) is going to be used after the form/page/whatever has finished.

Marc Gravell
That's great Marc, thanks - looks like I can't be lazy ;)
drjeks