Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unsubscribe from an event which uses a lambda expression?

I have the following code to let the GUI respond to a change in the collection.

myObservableCollection.CollectionChanged += ((sender, e) => UpdateMyUI()); 

First of all is this a good way to do this?

Second: what's the code to unsubscribe from this event? Is it the same but with -= (and then the complete anonymous method again)?

like image 300
Gerrie Schenck Avatar asked Apr 30 '09 07:04

Gerrie Schenck


People also ask

How to unsubscribe from an event in C#?

To unsubscribe in this scenario, go back to the code where you subscribe to the event, store the anonymous function in a delegate variable, and then add the delegate to the event.

Which of the following operator is used to unsubscribe any method from delegate reference?

The signature of the handler method must match the delegate signature. Register with an event using the += operator. Unsubscribe it using the -= operator.

Which operator would you use to have an event handler method subscribe to an event?

+= subscribes to an event. The delegate or method on the right-hand side of the += will be added to an internal list that the event keeps track of, and when the owning class fires that event, all the delegates in the list will be called.

What is the difference between lambda expression and anonymous methods?

A lambda expression is a short form for writing an anonymous class. By using a lambda expression, we can declare methods without any name. Whereas, Anonymous class is an inner class without a name, which means that we can declare and instantiate class at the same time.


2 Answers

First of all... yes its a good way of doing it, it's clean, small form and easy to read & understand... the caveat of course is "Unless you later want to unsubscribe".

I believe Jon Skeet pointed out before that "the specification explicitly doesn't guarantee the behaviour either way when it comes to equivalence of delegates created with anonymous methods."

So if you need to unsubscribe from the event at a later time, you'd be best to actually create a delegate instance so you can hang onto the reference for later.

var myDelegate = delegate(sender, e){UpdateMyUI()};  myObservableCollection.CollectionChanged += myDelegate;  myObservableCollection.CollectionChanged -= myDelegate; 
like image 146
Eoin Campbell Avatar answered Oct 11 '22 21:10

Eoin Campbell


If you need to unsubscribe from an event, you need an instanced reference. Unfortunately, that means you can't use that particular syntax.

like image 33
J. Steen Avatar answered Oct 11 '22 20:10

J. Steen