There are many articles on creating mathematical expression parsers (i.e. for displaying 3D functions where user inputs the formulas manually). Most of them are based on lexical analysis, grammar definitions etc. With C# there is a solution for making mathematical expression evaluator in a completely new way: by compiling code at runtime.
Let's assume that we want to create an application that would calculate 3D function like that:
z = f(x,y)
But we want to let the user input function formula manually (we don't know what the formula will look like).
A solution to deal with that task in 10 minutes is:
- Let the user input the function
- Compile that function into memory
- Run the function with given x and y
- Do something with result z value
To do that in a couple of minutes we would need a class with virtual method:
public class MyClassBase
public virtual double eval(double x,double y)
all we need more is a parser/evaluator class which would compile function body into assembly (created in memory) and calculate function result:
public class MathExpressionParser
MyClassBase myobj = null;
public bool init(string expr)
= new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.ICodeCompiler ic = cp.CreateCompiler();
= new System.CodeDom.Compiler.CompilerParameters();
cpar.GenerateInMemory = true;
cpar.GenerateExecutable = false;
string src = "using System;"+
"class myclass:MathEval.MyClassBase" +
"public override double eval(double x,double y)"+
"return "+ expr +";"+
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)
Type ObjType = cr.CompiledAssembly.GetType("myclass");
if (ObjType != null)
myobj = (MyClassBase)Activator.CreateInstance(ObjType);
catch (Exception ex)
public double eval(double x,double y)
double val = 0.0;
if (myobj != null)
val = myobj.eval(x,y);
Take a look at the init() method. All we need it to do is to create an assembly(in memory) with a class "myclass" derived from MyBaseClass. Note that "eval" method contains the formula given by the user at runtime. Also note that cpar.ReferencedAssemblies.Add("matheval.exe"); defines a reference to the application currently being created.
Then we can call myclass.eval method as many times as we want to:
MathExpressionParser mp = new MathExpressionParser();
Compiled code is of course much faster than any other solution used to parse and evaluate expressions.
A few things to do:
- Let the user input formulas as "xy*sin(x+y)" or "x^2+y^2" and convert them to c# "x*y*Math.Sin(x+y)" "x*x + y*y" etc...
- Do some error checking/handling other than compiler errors.
- Freeing and recreating the in-memory-assembly with another formula.
- Enjoy the code
PS: special thanks to AcidRain for some ideas