views:

3572

answers:

11

Is there a function the the .Net framework that can evaluate a numering expression contained in a string and return the numeric result? IE:

string mystring = "3*(2+4)";
int result = EvaluateExpression(mystring);
Console.Writeln(result);

prints 18.

Is there a standard framework function that you can replace my EvaluateExpression with ?

A: 

There is no such function.

You can however try JScript.Eval.

leppie
+3  A: 

You could fairly easily run this through the CSharpCodeProvider with suitable fluff wrapping it (a type and a method, basically). Likewise you could go through VB etc - or JavaScript, as another answer has suggested. I don't know of anything else built into the framework at this point.

I'd expect that .NET 4.0 with its support for dynamic languages may well have better capabilities on this front.

Jon Skeet
This is also incredibly bad performance.
Timothy Khouri
Yup. I would hope that the DLR will help on the performance side, at least a bit.
Jon Skeet
+11  A: 

Yes, you can let C# compiler evaluate it at runtime.

See: CSharpCorner

arul
Ok, so it's not a framework function, but it's more or less exactly what I'm looking for. Thanks
sindre j
Very interesting link. Thanks.
biozinc
A: 

Short answer: I don't think so. C# .Net is compiled (to bytecode) and can't evaluate strings at runtime, as far as I know. JScript .Net can, however; but I would still advise you to code a parser and stack-based evaluator yourself.

+2  A: 

There is not. You will need to use some external library, or write your own parser. If you have the time to do so, I suggest to write your own parser as it is a quite interesting project. Otherwise you will need to use something like bcParser.

DrJokepu
I know it's interesting, I've done it twice already, one with c and one with c++. I was just wondering if there was a built in possibility with cs/.net as it supports reflection I suspected it was a good possibility.
sindre j
+1  A: 

Here is a class that does complex math and date and time calculations in .NET. You can do the same on your own, but it takes a lots amount of time to write good parser:

http://www.geocities.com/alexei_cioina/cioinaeval.html

tomaszs
A: 

If you are able to specify your expression in RPN, you could write a parser in about a dozen or so lines of code.

Bob
+2  A: 

I recently needed to do this for a project and I ended up using IronPython to do it. You can declare an instance of the engine, and then pass any valid python expression and get the result. If you're just doing simple math expressions, then it would suffice. My code ended up looking similar to:

IronPython.Hosting.PythonEngine pythonEngine = new IronPython.Hosting.PythonEngine();
string expression = "3*(2+4)";
double result = pythonEngine.EvaluateAs<double>(expression);

You'd probably not want to create the engine for each expression. You also need a reference to IronPython.dll

Bearddo
+3  A: 

Hi,

You could look at "XpathNavigator.Evaluate" I have used this to process mathematical expressions for my GridView and it works fine for me.

Here is the code I used for my program:

public static double Evaluate(string expression)
{
    return (double)new System.Xml.XPath.XPathDocument
    (new StringReader("<r/>")).CreateNavigator().Evaluate
    (string.Format("number({0})", new
    System.Text.RegularExpressions.Regex(@"([\+\-\*])")
    .Replace(expression, " ${1} ")
    .Replace("/", " div ")
    .Replace("%", " mod ")));
}
Olav Botterli
+2  A: 

Try this:

static double Evaluate(string expression) {
  var loDataTable = new DataTable();
  var loDataColumn = new DataColumn("Eval", typeof (double), expression);
  loDataTable.Columns.Add(loDataColumn);
  loDataTable.Rows.Add(0);
  return (double) (loDataTable.Rows[0]["Eval"]);
}
Petar Repac
This is cool! This saved me many lines of code and/or a 3rd party component.
thames
+3  A: 

Using the compiler to do implies memory leaks as the generated assemblies are loaded and never released. It's also less performant than using a real expression interpreter. For this purpose you can use Ncalc which is an open-source framework with this solely intent. You can also define your own variables and custom functions if the ones already included aren't enough.

Example:

Expression e = new Expression("2 + 3 * 5");
Debug.Assert(17 == e.Evaluate());
Sébastien Ros
Exactly what I was looking for and works great.
Vyrotek