C # events - create specific event based on string

I am writing a class to handle events that go into a single event with a string value, and map them and prepare specific events based on the string value.

Everything works fine with a switch like

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 list of switches might be too long, so I would like it to display the string event for a handler in the data structure (like List of KeyValuePair), so I can just find the item for the string event and raise the associated event.

Any advice / ideas are most appreciated.

thank

+3


source to share


2 answers


You can just use a dictionary. However, be careful not to target delegates as lazy evaluating them. For this reason, delegates are immutable and thus you will not get 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);
}

      

+4


source


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 the toggle case use the below code

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

      

-1


source







All Articles