2

I am attempting to subscribe delegates to an event held in a List<KeyValuePair<KeyEnum, Delegate>

The goal is to associate a series of Handlers to keyboard keys and named axes, both of which are represented by Enums

Dispatching is fairly easy, I just iterate over the list of KVPs, check a condition, and if the condition is met, call the delegate simply with member.Value; I haven't encountered any issues with efficiency in processor time with this, and in fact, have found that it's significantly cleaner on the stack.

The issue is adding to the delegates after instantiated. Attempting to access it with collection.FirstOrDefault(n=>n.Key == KeyEnum.W).Value+= SomeMethod doesn't work, as Value is read only.

Is there a way to do this that doesn't require creating a new KeyValuePair every time, or a better solution than KeyValuePair in general

Azeranth
  • 151
  • 11
  • 2
    Why not use a `Dictionary`? – Sweeper Mar 13 '19 at 06:49
  • @sweeper Dictionary seemed like a waste of over head, since I'm already using Enums, look ups are faster not using the hashtable. Since I intend to be performing around a dozen lookups on this list every second, I thought that a dictionary would be innneficient to say the least. – Azeranth Mar 14 '19 at 07:44
  • `since I'm already using Enums, look ups are faster not using the hashtable.` - can you provide sources to this claim? – Sweeper Mar 14 '19 at 07:46

1 Answers1

0

Just use a Dictionary<KeyEnum, Action>. I don't see why you would need sequential access of the KVPs. You should also specify the delegate type corresponding to the event handlers if you can. Action or EventHandler or Action<Something> depending on your needs.

Then you can easily add and call delegates:

// adding delegates
if (dictionary.ContainsKey(KeyEnum.W)) {
    dictionary[KeyEnum.W] += SomeMethod;
} else {
    dictionary.Add(KeyEnum.W, SomeMethod);
}

// calling delegates
if (dictionary.ContainsKey(KeyEnum.W)) {
    dictionary[KeyEnum.W](...);
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313