Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# use string variable as a arithmetic operator

Tags:

c#

c#-4.0

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 = "+";
}
like image 553
Syed Abubakar Avatar asked Sep 17 '26 22:09

Syed Abubakar


2 Answers

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.

like image 57
Vadim Martynov Avatar answered Sep 20 '26 13:09

Vadim Martynov


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;
}
like image 34
shx Avatar answered Sep 20 '26 11:09

shx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!