2

I have a problem with NCalc: I'm trying to implement a way to add an expression to my program by writing it in a textbox and then have the program to use it to sum/multiply variables. Here is an example:

Expression expr = new Expression(textBox3.Text);
        expr.Parameters["a"] = 1;
        expr.Parameters["b"] = textBox2.Text;             
        textBox1.Text = expr.Evaluate().ToString();

I want to write the expression in textBox3 and the value of "b" variable in textBox2 and collect the result in textBox1. But if I try, for example, with:

  • textBox2 = "3"

  • textBox3 = "b+a"

the result is "31" instead of 4. What's wrong?

rene
  • 41,474
  • 78
  • 114
  • 152
Alewoor
  • 23
  • 2

1 Answers1

1

Because textBox2.Text is of type string, your parameter b is string "3" and not a number 3. If one parameter is string and another is number - NCalc (which works with strings too) will convert number to string, just like C# itself:

string s = "3" + 1; // 31

So to resolve this problem, convert string to number (of course it worth first checking if it can be converted):

int b;
if (int.TryParse(textBox2.Text, out b)) {
    Expression expr = new Expression(textBox3.Text);
    expr.Parameters["a"] = 1;
    expr.Parameters["b"] = b;      
    textBox1.Text = expr.Evaluate().ToString();
}
Evk
  • 98,527
  • 8
  • 141
  • 191