Evaluating string "3*(4+2)" yield int 18

sindre j picture sindre j · Dec 2, 2008 · Viewed 175.9k times · Source

Is there a function the .NET framework that can evaluate a numeric expression contained in a string and return the result? F.e.:

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

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

Answer

Ramesh Sambari picture Ramesh Sambari · Jun 14, 2012

If you want to evaluate a string expression use the below code snippet.

using System.Data;

DataTable dt = new DataTable();
var v = dt.Compute("3 * (2+4)","");