Monday 25 August 2014

C# - Evaluating Math Expressions at Runtime

There are third party Mathematical Expressions Evaluator libraries like NCalc (http://ncalc.codeplex.com/) which help you evaluate math expressions at runtime. But if your requirements are simple and do not want to get into the hazzles of third party references, you can make use of a hidden expression evaluator within .NET library.

It is Compute method within DataTable object that come to our help. Note that its not a static method and thus you have to use and instance of DataTable class.

using System.Data;
DataTable dt = new DataTable();
var result = dt.Compute("5*(4-2)","");
Console.WriteLine(result.ToString());

Happy Coding....