Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Possible Duplicate:
C# Adding and Removing Anonymous Event Handler

suppose I have an Action delegate declared this way:

public event Action<MenuTraverser.Actions> menuAction;

I am associating a method to it this way:

menuInputController.menuAction += (MenuTraverser.Actions action) => this.traverser.OnMenuAction(action);

Now, all works fine, but in certain situation I need to remove the delegated method and I don't know how. I tried this way but doesn't work:

menuInputController.menuAction -= (MenuTraverser.Actions action) => this.traverser.OnMenuAction(action);

How can I do such a thing? I need that my method OnMenuAction will be no longer called.

like image 545
Heisenbug Avatar asked Feb 04 '26 12:02

Heisenbug


2 Answers

You need to store a reference to a generic delegate into a field so later you can unsubscribe using this cached delegate field:

// declare on a class fields level
Action<MenuTraverser.Action> cachedHandler; 

// in constructor initialize
cachedHandler = (action) => this.traverser.OnMenuAction(action);

// subscribe
menuInputController.menuAction += cachedHandler;

// unsubscribe
menuInputController.menuAction -= cachedHandler;
like image 162
sll Avatar answered Feb 06 '26 01:02

sll


Since your signature seems to match (assuming that you have a void return type), you shouldn't need to add an anonymous function but you can use the method group directly:

menuInputController.menuAction += this.traverser.OnMenuAction;

And in this case unsubscribing should work as well:

menuInputController.menuAction -= this.traverser.OnMenuAction;
like image 40
Lucero Avatar answered Feb 06 '26 02:02

Lucero