0

I am working a c# method which calls different methods based on some conditions and I am wondering if I can do this without switch or if else statements. Below is the code I have

if (msg== atype)
{
    _aHandler.HandleAType(msg, TopicType.A);
}
else if (msg== btype)
{
    _
    _btype.HandleBType(msg, TopicType.B);
}
else if (msg== ctype)
{
    _cHandler.HandleC(msg);
}
else if (msg== dtype)
{
    _dHandler.HandleDType(msg);
}

else
    _logger.Error($"No matching type found for {msg}");

Please note that I have different methods with different types of parameters in each condition.

Is there a better way I can do this without switch/if-else ?

DoIt
  • 3,270
  • 9
  • 51
  • 103

1 Answers1

3

You mean something like this:

var dic = new Dictionary<string, Action>
{
    {atype, () => _aHandler.HandleAType(atype, TopicType.A)},
    {btype, () => _btype.HandleBType(btype, TopicType.B)},
    {ctype, () => _cHandler.HandleC(ctype)},
    {dtype, () => _dHandler.HandleDType(dtype)}
};

//Call it
dic[msg]();
Magnus
  • 45,362
  • 8
  • 80
  • 118