Reputation: 31
I'm new in C# and i'm trying to create a calculator. I'm storing a arithmetic operator in a string is there any way i can use the operator to solve the equation ?
My code :
else if (btn_name == "plus" || btn_name == "minus")
{
bol = true;
try
{
if (solve == "")
{
string num1 = Screen.Text;
first = float.Parse(num1);
second = first + second;
Screen.Text = second.ToString();
Screen_upper.Text = upper_text + text + " + ";
}
else
{
second = first (**#I want to use the operator here#**) second;
}
}
catch
{
Screen.Text = second.ToString();
Screen_upper.Text = upper_text + text + " + ";
}
solve = "+";
}
Upvotes: 3
Views: 1285
Reputation: 81
What I would think is the best way to do it, is to have a dictionary having key as the name of the operation and as the value a delegate, eg
var dict = new Dictionary<string, Func<int, int, int>> () {
{ "add", AddFunc },
{ "minus", MinusFunc }
};
public static int AddFunc(int arg1, int arg2)
{
return arg1 + arg2;
}
public static int MinusFunc(int arg1, int arg2)
{
return arg1 - arg2;
}
Calling the methods is as simple as dict["minus"](arg1,arg2)
Of course it would more sense to use Enums instead of strings but you get the idea.
Upvotes: 1
Reputation: 8902
You can use just if
or switch
operator and branches your logic for each else/case
block:
switch(btn_name)
{
case "plus":
second = first + minus;
break;
case "minus":
second = first - minus;
break;
case "div":
second = first / minus;
break;
}
But it's very difficult to read this code. The alternate solution is to to use predefined repository of operators. One way to implement it is to use simple Dictionary<string, Func<float, float, float>>
and delegate:
// it's class member, not a local variable
Dictionary<string, Func<float, float, float>> operators = new Dictionary<string, Func<float, float, float>>();
operators.Add("plus", (first, second) => first + second);
operators.Add("minus", (first, second) => first - second);
operators.Add("div", (first, second) => first / second);
Now you can use next code (completed your example):
if (solve == "")
{
string num1 = Screen.Text;
first = float.Parse(num1);
second = first + second;
Screen.Text = second.ToString();
Screen_upper.Text = upper_text + text + " + ";
}
else
{
second = operators[btn_name](first, second);
}
It can be better because you will split operators initialization and usage and make code bit clear.
Another one scenario is to have different event handler for each button and implement necessary logic inside the handler. But then you will need to refactor your code fore merge duplicated parts (number parsing and updating result) and your final solution will be nearly the same with dictionary based.
Upvotes: 3
Reputation: 43
No i think you can't. Check value you have in btn_name and if it's "minus" perform arithmetic operation
if (btn_name == "minus")
{
second = first - second;
}
Upvotes: 1