I want to call a method based on a value in a lookup table. The values will be looked up in a database, and will be iterated through. What I am trying to avoid is this:
foreach (Row r in rows)
{
if (r["command"] == "Command1")
MyClass.Command1();
else if (r["command"] == "Comman2")
MyClass.Command2();
else if (r["command"] == "Comman3")
MyClass.Command3();
}
This is legacy code that I have to support, but I know there surely is a better way to do this. Currently the code looks like the above but I am looking for a more elegant solution.
EDIT:
Based on the suggestions below, I am trying to do something like this:
static void Main(string[] args)
{
Dictionary<string, Action<MyClass>> myActions = new Dictionary<string,Action<MyClass>>();
myActions.Add("Command1",MyClass.DoCommand1("message1"));
myActions.Add("Command2",MyClass.DoCommand1("message2"));
myActions["Command1"]();
}
with my class file looking like this:
public class MyClass
{
public void DoCommand1(string message)
{
Console.WriteLine(message);
}
public void DoCommand2(string message)
{
Console.WriteLine(message);
}
}
However, I am getting syntax errors saying that an object reference is required for the nonstatic filed, method, or property MyClass.DoCommand1(string). Any ideas?
Please note I am using the .NET 2.0 framework.
You can use reflection:
Or you can also use delegates:
With delegates you get a nice syntax and avoid the performance hit of reflection.
UPDATE:
I noticed that you’re using .NET 2.0, you need to do:
UPDATE 2:: Now the example uses methods with a string parameter as seen in the updated question