Ian Hern
Ian Hern

Reputation: 669

How do I make a dictionary of events?

I want to have a dictionary of events, so far I have

private Dictionary<T, event Action> dictionaryOfEvents;

is it possible to do something like this?

Upvotes: 5

Views: 10787

Answers (3)

Ghominejad
Ghominejad

Reputation: 1798

You can't directly define a dictionary of event types but you can define the event inside a class instead.

private Dictionary<string, MyEventManager> dictionaryOfEvents;

dictionaryOfEvents["key1"].CallMyEvent();

Example implementation of MyEventManager Class :

public class MyEventManager {

   public event Action MyEvent;
   public void CallMyEvent => MyEvent.Invoke()
}

Upvotes: 2

TaW
TaW

Reputation: 54433

Event is not a type but Action is. So for instance you can write:

private void button1_Click(object sender, EventArgs e)
{
  // declaration
  Dictionary<string, Action> dictionaryOfEvents = new Dictionary<string, Action>();

   // test data
  dictionaryOfEvents.Add("Test1", delegate() { testMe1(); });
  dictionaryOfEvents.Add("Test2", delegate() { testMe2(); });
  dictionaryOfEvents.Add("Test3", delegate() { button2_Click(button2, null); });

  // usage 1
  foreach(string a in dictionaryOfEvents.Keys )
    {  Console.Write("Calling "  + a  +  ":"); dictionaryOfEvents[a]();}

  // usage 2
  foreach(Action a in dictionaryOfEvents.Values) a();

  // usage 3
  dictionaryOfEvents["test2"]();

}

void testMe1() { Console.WriteLine("One for the Money"); }        
void testMe2() { Console.WriteLine("One More for the Road"); }

Upvotes: 5

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73472

You can't have dictionary of events, though you can have dictionary of delegates.

private Dictionary<int, YourDelegate> delegates = new Dictionary<int, YourDelegate>();

where YourDelegate can be any delegate type.

Upvotes: 8

Related Questions