Nidere
Nidere

Reputation: 129

How to declare events inside a dictionary initialization?

I am creating a Dictionary of events and I want to declare those events inside the initialization of that dictionary instead of declaring them somewhere else and placing the links to the dictionary.

    static event EventDelegate Event1;
    static event EventDelegate Event2;
    static event EventDelegate Event3;

    public enum EventTypes
    {
        Event1, 
        Event2,
        Event3,
    }

    public static Dictionary<EventTypes, EventDelegate> events = new Dictionary<EventTypes, EventDelegate>
    {
        {EventTypes.Event1, Event1},
        {EventTypes.Event2, Event2},
        {EventTypes.Event3, Event3},
    };

So I want to do something like that:

{EventTypes.Event1, new event EventDelegate Event1}

Is that possible?

Upvotes: 3

Views: 522

Answers (2)

Enigmativity
Enigmativity

Reputation: 117064

If you define your dictionary like this:

public delegate void EventDelegate(object data);

public static Dictionary<EventTypes, EventDelegate> Events =
    new Dictionary<EventTypes, EventDelegate>
    {
        { EventTypes.Event1, (EventDelegate)((_) => { }) },
        { EventTypes.Event2, (EventDelegate)((_) => { }) },
        { EventTypes.Event3, (EventDelegate)((_) => { }) },
    };

public enum EventTypes
{
    Event1,
    Event2,
    Event3,
}

Then this code works a treat:

Events[EventTypes.Event1] += (object data) => Console.WriteLine($"Event1 (1): {data}");
Events[EventTypes.Event1] += (object data) => Console.WriteLine($"Event1 (2): {data}");
Events[EventTypes.Event2] += (object data) => Console.WriteLine($"Event2: {data}");

Events[EventTypes.Event1]("A");
Events[EventTypes.Event2]("B");
Events[EventTypes.Event3]("C");

The output I get is:

Event1 (1): A
Event1 (2): A
Event2: B

You are then clearly declaring those events inside the initialization of the dictionary.

Upvotes: 0

Thomas Hilbert
Thomas Hilbert

Reputation: 3629

How about wrapping the events?

class MyEventWrapper
{
    public event EventDelegate Handlers;

    public void Raise(object sender, EventArgs args)
    {
        Handlers?.Invoke(sender, args);
    }
}

//

Dictionary<EventTypes, MyEventWrapper> eventMap = new Dictionary<EventTypes, MyEventWrapper>
{
    { EventTypes.Event1, new MyEventWrapper() },
    { EventTypes.Event2, new MyEventWrapper() },
};

//

eventMap[EventTypes.Event1].Handlers += (s, a) => { };
eventMap[EventTypes.Event2].Handlers += (s, a) => { };

//

eventMap[EventTypes.Event1].Raise(this, new EventArgs());

Upvotes: 5

Related Questions