user1965804 user1965804 - 1 month ago 12
C# Question

How to dynamically assign method combobox

I have several methods that I want to execute according to the selected value of a combobox.
I'm currently using the following code:

switch (comboBox1.SelectedIndex)
{
case 1:
// call method1
break;
case 2:
// call method2
break;
}


Is there a good way to get the same thing like if
combobox.selectedIndex == 1
then auto call to method 1?

Answer

The simplest way is through the use of delegates:

private readonly Dictionary<int, Action> actions = new Dictionary<int, Action>
  {
    { 1, Method1 },
    { 2, Method2 },
    { 3, Method3 },
  };

Which allows you to do something like this:

actions[comboBox.SelectedIndex]();

You could also use reflection, of course, but keeping things statically linked has plenty of benefits :)