I have two lists, one with events, one with Actions(functions)
The reason for the lists is to allow a user to connect the two together through an interface. So I am trying to create a method which takes the event and has the action added to it.
I want to be able to do TheEvent += TheAction, and then be able to remove it later with -=.
I am sorry if how to do this is obvious, I couldn’t come up with the right keywords to search for, “connect action to event” is the best I thought of and it is pretty useless in a search.
Nothing I have come up with will allow me to add an action to an event, but perhaps I am going about it wrong. Any advice on the best way to allow a user to select an event and a function to trigger from the event would be appreciated.
Events are immutable. If you add or remove an event handler, a new event (or multicast delegate) is created. This also means, that you must be careful when adding events to a list. This will not work
If you add an event handler to
Event0the corresponding list entry will still reference the oldEvent0! If you add an event handler toEvents[1],Event1will not be updated!I do not know if this is what you mean, however, if you have these two lists
You can add en event hander (an action) to an event like this:
and raise an event like this
EDIT (in response to your comment):
Here again, you must act on the original event list and not on an event passed as parameter, because of this immutable problem explained above. If necessary, you could also pass the list itself as an additional parameter.
For your other problem of how to let the user select events and actions, I would suggest of either having four lists, where as the events and action lists would be paralleled with two corresponding string lists with the names of the events and actions. Alternatively, you could wrap the events and actions in a class containing them and their names
Then you would define the lists like this
Now you can use these lists directly as data source in combo boxes or list boxes. The overridden
ToStringmethods of the wrappers automatically provide a string to display.The add method can now be rewritten as
The wrappers also defuse the immutable situation, since we do not pass the event as parameter but its wrapper.