C# event += and -= not handled properly on Java

Hi!

I found a bug on the Java implementation for event handling on the += and -=.

    private static event Action<string> OnAction;
    
    private static void OnActionHandler(string m)
    {
        writeLn("OnActionHandler: " + m);
    }
    
    public static Int32 Main(string[] args)
    {
        
         if (OnAction != null) OnAction("A");
         
         OnAction += OnActionHandler;
         OnAction += OnActionHandler;
         OnAction("B");
         
         OnAction -= OnActionHandler;
         OnAction("C");

         OnAction -= OnActionHandler;
         if (OnAction != null) OnAction("D");
    }

On .NET this will output:

OnActionHandler: B
OnActionHandler: B
OnActionHandler: C

On Java it does output:

OnActionHandler: B
OnActionHandler: B
OnActionHandler: C
OnActionHandler: C
OnActionHandler: D
OnActionHandler: D

The generated code looks like:

    if ($_OnAction != null) {
        raiseOnAction("A");
    }

    addOnAction(new Program$1());
    addOnAction(new Program$2());
    raiseOnAction("B");
    removeOnAction(new Program$3());
    raiseOnAction("C");
    removeOnAction(new Program$4());
    if ($_OnAction != null) {
        raiseOnAction("D");
    }

I think the fix is to not create new $X for each call to += or -=, but instead create one per OnHandler and implement equal/hashCode so the List.remove method can effectively find it.

Something like:

    addOnAction(new Program$1());
    addOnAction(new Program$1());
    raiseOnAction("B");
    removeOnAction(new Program$1());
    raiseOnAction("C");
    removeOnAction(new Program$1());

Thanks!

Thanks, logged as bugs://84198

Indeed, that’s silly/broken…

bugs://84198 got closed with status fixed.