0

I am developing an app of windows phone 8.1. I want to execute an expression at run time that is stored in a string variable. For Example:

string exp = "4+5-2";

I can do this in desktop application by following code:

MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
sc.Language = "VBScript";
object result = sc.Eval(expr);

But this code is not working there. It causes application to crash.

Saravanan Sachi
  • 2,572
  • 5
  • 33
  • 42
Bilal
  • 558
  • 8
  • 18
  • 2
    possible duplicate of [c# evaluating string "3\*(4+2)" yield int 18](http://stackoverflow.com/questions/333737/c-sharp-evaluating-string-342-yield-int-18) – LiamK Apr 17 '15 at 19:12
  • No, i need help in a code that can be executed on windows phone app. – Bilal Apr 17 '15 at 19:17
  • Can't you use the answer in LiamK's comment that Sébastien Ros - MSFT posted? – John Odom Apr 17 '15 at 19:19
  • Or the answer here: http://stackoverflow.com/questions/5838918/evaluate-c-sharp-string-with-math-operators (if Ncalc can't be used, other questions have found that Jace.NET works well for WP8 apps) – LiamK Apr 17 '15 at 19:22
  • Ncalc isnt working i have tried ... – Bilal Apr 17 '15 at 19:25

2 Answers2

1

If you don't want to use any the packages suggested in the duplicate questions or comments and really just want to roll your own parser, then the Shunting-yard algorithm is as good as any. Take the pseudo-code from Wikipedia and implement it in C#.

As a bonus, you could probably add some logic to go beyond basic arithmetic operations with that algorithm if you really need it (e.g. support invoking a function by name).

LiamK
  • 795
  • 6
  • 16
1

You could use Jace.NET(Just Another Calculation Engine) nuget package. It supports WP8.1:

 private CalculationEngine engine = new CalculationEngine();

 private void ExecuteButton_Click(object sender, RoutedEventArgs e)
 {
    double result = engine.Calculate(ExpressionTextBox.Text);
    ExpressionTextBox.Text = result.ToString();  // displays the result
 }

For more info check this link and its repository on Github.

ocuenca
  • 38,548
  • 11
  • 89
  • 102