Geoff Kell
Geoff Kell

Reputation: 31

C# Events - Raising specific event based on string

I am writing a class to process events coming in on a single event with a string value and map them to and raise specific events based on the string value.

It all works fine with a switch such as

SpecificHandler handler = null;
SpecificArgs args = new SpecificArgs(Id, Name);   
switch (IncomingEventName)
{ 
    case "EVENT1":
        handler = Event1Handler;
        break;
    case "EVENT2":
        handler = Event2Handler;
        break;
    ... etc
}
if (handler != null) handler(this, args);

But the switch list can get far too long so I'd like a way so map the string event to the handler in a data structure (e.g. List of KeyValuePair) so I can just locate the item for the string event and raise the associated event.

Any tips/ideas most welcome.

Thanks

Upvotes: 3

Views: 469

Answers (2)

Georg
Georg

Reputation: 5771

You can just use a dictionary. However, be careful to not target the delegates but lazy evaluations of them. As a reason, delegates are immutable and thus you would not receive any event handlers, otherwise.

private static Dictionary<string, Func<Yourtype, SpecificHandler>> dict = ...
dict.Add("Foo", x => x.FooHappened);
dict.Add("Bar", x => x.BarHappened);

and use it like this:

Func<SpecificHandler> handlerFunc;
SpecificArgs args = new SpecificArgs(...);
if (dict.TryGetValue(IncomingEventName, out handlerFunc))
{
    SpecificHandler handler = handlerFunc(this);
    if (handler != null) handler(this, args);
}

Upvotes: 4

Null Pointer
Null Pointer

Reputation: 9289

Initialize a dictionary with event name as key and event handler as value .Then you can easily access the event handler.

//initialize the dictionary

     Dictionary<string,EventHandler> dic=new Dictionary<string, EventHandler>();
     dic["EVENT1"] = Event1Handler;

and instead of switch case use the below code

            if (dic.ContainsKey(IncomingEventName))
            {
                var handler = dic[IncomingEventName];
                if (handler != null) handler(this, args);
            }

Upvotes: -1

Related Questions