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 = "+";
}
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With