If there is a switch statement or a series of if/else statements, then we could use dictionary. For example, “key” is an integer and if “key” == 1 function PerformActionA() is called, if “key” == 2 function PerformActionB() is called and if “key” == 3 function PerformActionC() is called. The following is switch statement for this example:
switch (key)
{
case 1:
//perform action a
PerformActionA();
break;
case 2:
//perform action b
PerformActionB();
break;
case 3:
//perform action C
PerformActionC();
break;
}
We can simplify the above statement into a dictionary. The following are the steps to do so:
- Create a Dictionary: The very first step is to create a dictionary:
- TKey: The dictionary key’s type is the type of the switch statement’s argument. For example, if we are comparing strings to determine the case, then the key of the dictionary will be a string. On the other hand if we are comparing integers, then the key is an integer. In the above example since “key” is an integer, then the dictionary’s key is an integer.
- TValue: The value’s type will be either “Action” (if functions do not return values) or “Func” (If functions do return values). In the example above, since the functions PerformActionA(), PerformActionB(), and PerformActionC() do not return value, then the type will be “Action”.
Therefore for the example above, the dictionary of methods will be:
Dictionary<int, Action> methodList = new Dictionary<int, Action>();
- Add records to Dictionary: For every case, add the case key value as dictionary’s key and the method name as dictionary’s value. For the example above we’ll have:
methodList.Add(1, PerformActionA);
methodList.Add(2, PerformActionB);
methodList.Add(3, PerformActionC);
- Call the Dictionary: To use the dictionary, first check to ensure the key value exists in the dictionary. If the value exists, then the dictionary’s name followed by the key value in brackets and () is the format. For the above example it will be:
int key = 2;
if (methodList.ContainsKey(key))
{
methodList[key]();
}