Just another tech site

C# Dynamic Math Expression Evaluation


Dyamicaly generation of a Class that will evaluate the Mathematical expression.

namespace ns
{ 
   using System; 
   class class1
   { 
        public static decimal Eval()
        {
             return Convert.ToDecimal(MathExpression );
        }
   }
}

the class will be exceuted.
Here is the complete code

using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

namespace TANITLibrary.MathEvaluation
{
    public class CMathEvaluation
    {
        public decimal Evaluate(string MathExpression)
        {
            decimal result = 0;
            try
            {
                CSharpCodeProvider codeProvider = new CSharpCodeProvider();
                CompilerParameters compilerParameters = new CompilerParameters();
                compilerParameters.GenerateExecutable = false;
                compilerParameters.GenerateInMemory = false;

                string tmpModuleSource = "namespace ns{" 
+ "using System;" 
+ "class class1{" 
+ "    public static decimal Eval(){"
+"          return Convert.ToDecimal("+ MathExpression + ");"
+"     }"
+"}} ";

                CompilerResults compilerResults = codeProvider.CompileAssemblyFromSource(
                                                  compilerParameters, tmpModuleSource);
                if (compilerResults.Errors.Count > 0)
                {
//If a compiler error is generated, we will throw an exception because 
//the syntax was wrong - again, this is left up to the implementer to verify 
//syntax before calling the function.  The calling code could trap this in a 
//try loop, and notify a user  
//the command was not understood, for example.
                    throw new ArgumentException("Expression cannot be evaluated [" + MathExpression + "]");
                }
                else
                {
                    MethodInfo Methinfo = compilerResults.CompiledAssembly.GetType("ns.class1").GetMethod("Eval");
                    result = (decimal)Methinfo.Invoke(null, null);
                }
            }
            catch (Exception Ex)
            {
                throw new ArgumentException("Expression cannot be evaluated, please use a valid C# expression [" + MathExpression + "] -- Ex[" + Ex.Message + "][" + Ex.InnerException + "]");
            }
            return result;
        }
    }
}

So let’s call the piece of code

string mathExpression = "(1+1)*3";
            Console.WriteLine(String.Format("{0}={1}",mathExpression, Evaluate(mathExpression)));
            mathExpression = "20+1";
            Console.WriteLine(String.Format("{0}={1}", mathExpression, Evaluate(mathExpression)));

the result

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Tag Cloud

%d bloggers like this: