whackatoe whackatoe - 2 months ago 7
C# Question

Pass enum elements as event args C#

Is it possible to pass Enum elements as event arguments ?

Let's say I have..

public class Letters
{
public delegate void StateChangedEventHandler(object sender, EventArgs e);
public event StateChangedEventHandler StateChanged;

public AbcState state = AbcState.Aaa;
public AbcState State
{
get{return this.state;}
set
{
this.state = value;
this.OnStateChanged();
}
}

public enum AbcState
{
Aaa,
Bbb,
Ccc
}

protected virtual void OnStateChanged()
{
StateChanged?.Invoke(this, State);
}


See how I am trying to pass the element of the enum as an event argument?
Now, I normally would create a class and extends EventArgs, and then I would be able to pass the class itself.
And I know I could do the same here, Create a different class extending EventArgs and then create the enum, field and property right in the class. And then make an instance of the latter into my class "Letters" (used in code above).

But, isnt that crazy ? There has to be a better way. Please tell me there is a simplier way.

By the way I do not know if the code above would compile I just wrote it straight in the Editor as I am not on my dev computer right now.

Answer

If you want the parameter of the event to be the enum, then sure, just specify that as the signature when declaring the event:

public class Letters
{
    public event Action<AbcState> StateChanged;

    private AbcState state = AbcState.Aaa;     
    public AbcState State
    {
        get{return this.state;}
        set
        {
            this.state = value;
            this.OnStateChanged();
        }
    }

    public enum AbcState
    {
        Aaa,
        Bbb,
        Ccc
    }

    protected virtual void OnStateChanged()
    {
        StateChanged?.Invoke(State);
    }
}