Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event unsubscription via anonymous delegate [duplicate]

I am using Resharper 5.1 code analysis many a times i get a comment from resharper as

"Event unsubscription via anonymous delegate"

#Part of Code  

if (((bool)e.NewValue))
{
    listView.PreviewTextInput += (o,args) =>
        listView_PreviewTextInput(o,args,listView);
}
else
{
    listView.PreviewTextInput -= (o, args) => 
        listView_PreviewTextInput(o, args, listView);
}

How could i correct or optimze this thing

like image 595
Ankesh Avatar asked Jan 10 '12 12:01

Ankesh


People also ask

Why do we use anonymous event handlers in Windows Forms?

Anonymous methods are a simplified way for you to assign handlers to events. They take less effort than delegates and are closer to the event they are associated with. You have the choice of either declaring the anonymous method with no parameters or you can declare the parameters if you need them.

Should I unsubscribe from events c#?

In order to prevent resource leaks, you should unsubscribe from events before you dispose of a subscriber object. Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler.

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.


1 Answers

You can extract the lamdba to a variable:

EventHandler func = (sender, e) =>
    listView_PreviewTextInput(sender, e, listView);

if (((bool)e.NewValue))
{
    listView.PreviewTextInput += func;
}
else
{
    listView.PreviewTextInput -= func;
}
like image 57
Steven Avatar answered Oct 16 '22 23:10

Steven