If I have a string with a valid math expression such as:
String s = \"1 + 2 * 7\";
Is there a built in library/function in .NET that will p
Initially I used the c# wrapper for muparser. This was very fast. The only faster solution I know is exprtk. If you are looking for other solutions you can checkout the benchmark.
But in case of .Net you can use the builtin support to compile code at runtime. The idea is to have a "template" source file as e.g. embedded resource where you can replace the formula for the evaluation. Then you pass this prepared class-source-code to the compiler.
A basic template could look like this:
public class CSCodeEvaler
{
public double EvalCode()
{
return last = Convert.ToDouble(%formula%);
}
public double last = 0;
public const double pi = Math.PI;
public const double e = Math.E;
public double sin(double value) { return Math.Sin(value); }
public double cos(double value) { return Math.Cos(value); }
public double tan(double value) { return Math.Tan(value); }
...
Notice the %formula% where the expression will be put in.
To compile use the class CSharpCodeProvider. I do not want to put in the complete source here. But this answer might help:
After you have the in memory assembly loaded you can create an instance of your class and call EvalCode.