public event Action - can only appear on the left hand side

While poking around learning c# I stumbled upon this code, it’s from working example so obviously code worked and now unity throws error The event ‘Test.OnMove’ can only appear on the left hand side of += or -=.

I’m a newbie, can somebody help and explain how this worked without private event “private event Action _onMove” because I found that people recomend that for this error.

public class Test : MonoBehaviour
    {
        public event Action<Test> OnMove
        {
            add
            {
                Action<Test> action = this.OnMove;
                Action<Test> action2;
                do
                {
                    action2 = action;
                    action = Interlocked.CompareExchange(ref this.OnMove, (Action<Test>)Delegate.Combine(action2, value), action);
                }
                while (action != action2);
            }
            remove
            {
                Action<Test> action = this.OnMove;
                Action<Test> action2;
                do
                {
                    action2 = action;
                    action = Interlocked.CompareExchange(ref this.OnMove, (Action<Test>)Delegate.Remove(action2, value), action);
                }
                while (action != action2);
            }
        }
    }

You can’t do that. What’s wrong with the default implementation (i.e. no explicit add & remove implementation) ?

It won’t work, because you cannot assign an explicitly implemented event to something. You have to use the backing delegate (or another backing event, which yet again has its backing delegate). In addition to that, in your specific case that’d even be a recursive call which would cause a stack overflow, as the add-modifier would depend on itself ("in order to add something, it calls add, which calls add, which calls add …).

1 Like

What confused me is that the example is from the working code, so it can be assumed that this example should not work but I guess it somehow works, thanks Suddoha!

Where’s that example from?