Be sure when you ever have a code that it has the chain of if else there should be an improvement. (even many programmers say you should not use if statement in your code as possible and some others say don't use else statement at all!)
You can use something like this:
First Add
a class to manage your actions:
public class ActionRegistry: Dictionary<string, Func<int, int, int>>
{
public ActionRegistry()
{
this.Add("Add", (x, y) => x + y);
this.Add("Subtract", (x, y) => x - y);
}
}
Then you can use that class like this:
public class DoStuff
{
private int Calculate(string sAction)
{
var actionRegistry= new ActionRegistry();
var a = 1;
var b = 2;
//var actionResult= actionRegistry[this should come from your drop down].Invoke(a, b);
var actionResult= actionRegistry[sAction].Invoke(a, b);
//you can even Register New Action Like this :
actionRegistry.Add("Multiply",(x,y)=>x*y);
//then you can use it somewhere else:
var multiplyResult = actionRegistry["Multiply"].Invoke(a, b);
return actionResult;
}
}
Every time your action has changed you just need to add the new action in your ActionRegistry
. With this approach, there is no need for that if-else statement.
By the way, you can even use interface and DI to loosely couple the ActionManager
.
UPDATE Here my update using enums:
First Declare an Enum :
enum ActionType
{
Add,
Subtract
}
Then use that enum in your ActionRegistry class:
public class ActionRegistry: Dictionary<int, Func<int, int, int>>
{
public ActionRegistry()
{
//it's better to register your actions outside the class
// and don't use enum inside your class
// but for simplicity i did that inside the class
this.Add((int)ActionType.Add, (x, y) => x + y);
this.Add((int)ActionType.Subtract, (x, y) => x - y);
}
}
then you should change your calculate method like this :
private int Calculate(int actionTypeCode)
{
var actionRegistry= new ActionRegistry();
var a = 1;
var b = 2;
//var actionResult= actionRegistry[this should come from your drop down].Invoke(a, b);
var actionResult= actionRegistry[actionTypeCode].Invoke(a, b);
return actionResult;
}
Note that you should bind your dropdown list with your enum keys as value.
I prefer to use an integer as my key because I can add more item later without changing my enum but it is not necessary.