0

How to use event in method argument? I'm trying to write method to unsubscribe all anonymous event handlers. In this example UnsubscribeAll() is working, but UnsubscribeAll(Action eventAction) isn't.

public class Foo
{
    public event Action SomeEvent;

    public void UnsubscribeAll(Action eventAction)
    {                    
        if(eventAction is null)
            return;
        var delegates = eventAction.GetInvocationList();
        for (int i = 0; i < delegates.Length; i++)
        {
            Action action = (Action) delegates[i];
            if(action != null && SomeEvent != null)
                eventAction -= action;
        }
    }

    public void UnsubscribeAll()
    {                    
        if(SomeEvent is null)
            return;
        var delegates = SomeEvent.GetInvocationList();
        for (int i = 0; i < delegates.Length; i++)
        {
            Action action = (Action) delegates[i];
            if(action != null && SomeEvent != null)
                SomeEvent -= action;
        }
    }
}
  • What do you mean by "isn't working"? – Sweeper Jul 02 '21 at 13:34
  • Your edit is not answering my question. _How_ does it not work? Does it do something you did not expect? What is that something you did not expect? Describe it? Does it produce an error? What is the error message? How did you try to call `UnsubscribeAll(Action eventAction)`? – Sweeper Jul 02 '21 at 13:40
  • @Sweeper This method just not unregister handlers, Array delegatesDestroyed contains all handlers, but after calling method, it contains it all the same. – Алексей Гребцов Jul 02 '21 at 13:46
  • That's because @АлексейГребцов a new delegate is created when you call the subtraction operator, which in turn calls the static method `Delegate.Remove()`, what happens is a new invocation list is created, which won't contain the specified `value` you wanted to remove, out of which a new multicast delegate is created via a internal method, `NewMulticastDelegate`. If you add `ref` to your `eventAction` parameter your function will work: `public void UnsubscribeAll(ref Action eventAction)`. – Space Jul 02 '21 at 13:53
  • @Space And how would you call that `UnsubscribeAll(ref Action eventAction)`? – GSerg Jul 02 '21 at 13:57

0 Answers0