Alex Rivera | Logout

Best and shortest way to evaluate mathematical expressions

Asked 2009-09-17T10:27:07.783
18

There are many algorithms to evaluate expressions, for example:

  1. By Recursive Descent
  2. Shunting-yard algorithm
  3. Reverse Polish notation

Is there any way to evaluate any mathematical expression using C# .net reflection or other modern .net technology?

Edit
Report

1 Answer

3

Although using compiler services is a simple and efficient solution, it raises serious security issues if the expression is entered by a user, because it could execute virtually anything.

There's another very simple solution that is much more secure : take advantage of the JScript Eval function. You just need to follow these steps :

Create a js file named JsMath.js :

class JsMath
{
    static function Eval(expression : String) : double
    {
        return eval(expression);
    };
}

Compile it into a class library :

jsc /t:library JsMath.js

Reference the JsMath library in your C# project, and use it like that :

double result = JsMath.Eval(expression);
answered 2009-09-17T12:20:34.297

Your Answer