1

I am assigning a delegate as a event handler, from within this delegate I need too remove the delegate as the handler, eg

wb.DocumentCompleted += delegate(object sender_, WebBrowserDocumentCompletedEventArgs e_)
{
    if (condition)
    {
        wb.DocumentCompleted -= this;
    }
};

The above is erroneous code

cannot implicitly convert 'x.Form1' to 'System.Windows.Forms.WebBrowserDocumentCompletedEventHandler'

How would I do this? Any help appreciated.

BinkyNichols
  • 586
  • 4
  • 14
  • is part of the error missing? have you already tried to use a method instead of an anonymous method when adding and removing the delegate? – Giulio Caccin Aug 15 '19 at 19:47
  • @Giulio Caccin I need to have an inline delegate, cos the code needs to change in a for loop, dynamic event handler for dynamically made components – BinkyNichols Aug 15 '19 at 19:51
  • 2
    @BinkyNichols Check the answer here: https://stackoverflow.com/questions/35074591/c-sharp-remove-event-from-browser – Juan S.Montoya Aug 15 '19 at 19:53

1 Answers1

2

assuming that object sender_ is this wb object.

 wb.DocumentCompleted -= YOUR DELEGATE HERE

however with an anonymous delegate this is impossible without assigning it to a variable first. So assuming that delegates can be assigned to variables

 var del = delegate(object sender....
 wb.DocumentCompleted += del

this is the classical caveat of anonymous functions in general, you must cache a reference to it at some point to refer to it again, in this case to specify it for removal.

that would be the minimum requirement if you want to explicitly remove that delegate and not other delegates that could also already be on the object, which i would expect is your goal if there is a reason to remove the delegate in the first place as event handler memory leaks just aren't an issue in c# forms

However if you want to remove all eventhandlers on the event then you can simply call

 wb.DocumentCompleted = null;

depending on your library and framework(this appears to be windows forms in your case) you may need to handle adding and removing event handlers differently. event handling is slightly different between many C# frameworks and versions. you can refer to any of many stack overflow questions to learn how to affect the list of event handlers on an event these days most of them support -= but reflection is also an option

How to remove all event handlers from an event

How can I clear event subscriptions in C#?

How to remove a method from an Action delegate in C#

in fact here is a question that is just what you have asked.

Adding and Removing Anonymous Event Handler

Jody Sowald
  • 342
  • 3
  • 18