2

Hi so am trying to make this event change when the state is updated for some reason it's not allowing me to compile it's giving the error:

The event 'Entity.StateChanged' can only appear on the left hand side of += or -=

I don't know what's wrong it seems right i tried google it did not help

public Entity.State state
{
    get
    {
        return this._state;
    }
    set
    {
        if (this._state != value)
        {
            this._state = value;
            this.OnStateChanged();
        }
    }
}

protected virtual void OnStateChanged()
{
    if (this.StateChanged != null)
    {
        this.StateChanged();
    }
}

public event Action StateChanged
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    add
    {
        this.StateChanged += value;
    }
    [MethodImpl(MethodImplOptions.Synchronized)]
    remove
    {
        this.StateChanged -= value;
    }
}

Thank you guy's for your time and help!

Eugene Podskal
  • 10,270
  • 5
  • 31
  • 53
Reptic
  • 175
  • 3
  • 4
  • 13
  • 1
    I don't know about the given error, but writing `this.StateChanged += value` in the add handler of `StateChanged` sounds like a good way to get a Stack Overflow – BradleyDotNET Jan 13 '17 at 19:05
  • Why are you adding custom add/remove handlers in the first place? – Servy Jan 13 '17 at 19:05
  • Is there a way to fix the Stack Overflow problem, Also i am testing the event action i'm learning so sorry! – Reptic Jan 13 '17 at 19:07
  • Possible duplicate of [-event- can only appear on the left hand side of += or -=](https://stackoverflow.com/questions/4496799/event-can-only-appear-on-the-left-hand-side-of-or) – StayOnTarget Feb 20 '19 at 17:06

1 Answers1

5

If one implements custom events accessor, then he has to provide a backing delegate field that will be used to store added callbacks:

protected virtual void OnStateChanged()
{
    var stateChanged = this._stateChanged;
    if (stateChanged == null)
        return;

    stateChanged();
}

private Action _stateChanged;

public event Action StateChanged
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    add
    {
        this._stateChanged += value;
    }
    [MethodImpl(MethodImplOptions.Synchronized)]
    remove
    {
        this._stateChanged -= value;
    }
}

But why does it work with standard/non-custom events like public event Action StateChanged;?

Because compiler automatically generates a backing field for that event and you can get get it with var action = this.StateChanged;, but you should know that events are not fields - they are a pair of methods - add, remove. It is the compiler that contextually accesses event's autogenerated backing field when you do var action = this.StateChanged;.

Community
  • 1
  • 1
Eugene Podskal
  • 10,270
  • 5
  • 31
  • 53