This question already has an answer here:
- Unsubscribe anonymous method in C# 11 answers
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
Warning! Accepted answer from Steven is wrong, all it does is just masking a problem that resharper is warning about.
Every time given code is executed
you'll get a fresh (since you may capture different
listView
) instance of anonymous delegate saved tofunc
, an instance that's not subscribed to any events yet, so in turn this codewill effectively do nothing, since you cant unsubscribe from an event you're not subscribed to. This will lead to mind-boggling bugs like event handlers 'called twice', memory leaks etc.
Actually, Jon Skeet says it may work in some cases:
e.g. when compiler doesn't generate new instance every time, you'll see nice behavior.
But that's not reliable and certainly wouldn't work in case described in starter question with captured variable
listView
.So my suggestion is:
Use anonymous functions as event handlers ONLY if you will never have to unsubscribe.
You can extract the lamdba to a variable: