Click here to Skip to main content
13,350,486 members (67,685 online)
Click here to Skip to main content
Add your own
alternative version


96 bookmarked
Posted 20 Apr 2002

Runtime C# Expression Evaluator

, 20 Apr 2002
Rate this:
Please Sign up or sign in to vote.
A C# class (and library if needed) to do runtime evaluations of C# expressions
<!-- Download Links --> <!-- Add the rest of your HTML here -->


This is a simple class library (or just .cs file if you wish) to allow for runtime compilation and evaluation of C# code blocks. There are both static methods of the Evaluator class that allow for simple use (but at a performance penalty) or you can use the object directly to create multiple evaluations:

Console.WriteLine("Test0: {0}", Evaluator.EvaluateToInteger("(30 + 4) * 2"));
Console.WriteLine("Test1: {0}", Evaluator.EvaluateToString("\"Hello \" + \"There\""));
Console.WriteLine("Test2: {0}", Evaluator.EvaluateToBool("30 == 40"));
Console.WriteLine("Test3: {0}", Evaluator.EvaluateToObject("new DataSet()"));

EvaluatorItem[] items = {
                          new EvaluatorItem(typeof(int), "(30 + 4) * 2", "GetNumber"),
                          new EvaluatorItem(typeof(string), "\"Hello \" + \"There\"", 
                          new EvaluatorItem(typeof(bool), "30 == 40", "GetBool"),
                          new EvaluatorItem(typeof(object), "new DataSet()", "GetDataSet")

Evaluator eval = new Evaluator(items);
Console.WriteLine("TestStatic0: {0}", eval.EvaluateInt("GetNumber"));
Console.WriteLine("TestStatic1: {0}", eval.EvaluateString("GetString"));
Console.WriteLine("TestStatic2: {0}", eval.EvaluateBool("GetBool"));
Console.WriteLine("TestStatic3: {0}", eval.Evaluate("GetDataSet"));

How does it work? I am using the CodeDOM to create a simple assembly with a single class in it. I simply transform each of the EvaluatorItems into a method of the class. When you call EvaluateInt() or Evaluate(), I use reflection to get a MethodInfo object and call the method.

The source code comes packaged in a Class Library with a Test program that you can use to get examples of use:

To compile the expressions, I am creating a new CSharpCodeProvider and setting Compiler attributes (like adding references, telling it to generate it in memory, etc.). Then I am building a dummy class that I can append my methods on. Lastly I compile it (check for errors) and save the object to use to call with the MethodInfo structure:

ICodeCompiler comp = (new CSharpCodeProvider().CreateCompiler());
CompilerParameters cp = new CompilerParameters();
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;

StringBuilder code = new StringBuilder();
code.Append("using System; \n");
code.Append("using System.Data; \n");
code.Append("using System.Data.SqlClient; \n");
code.Append("using System.Data.OleDb; \n");
code.Append("using System.Xml; \n");
code.Append("namespace ADOGuy { \n");
code.Append("  public class _Evaluator { \n");
foreach(EvaluatorItem item in items)
  code.AppendFormat("    public {0} {1}() ", 
  code.Append("{ ");
  code.AppendFormat("      return ({0}); ", item.Expression);
code.Append("} }");

CompilerResults cr = comp.CompileAssemblyFromSource(cp, code.ToString());
if (cr.Errors.HasErrors)
  StringBuilder error = new StringBuilder();
  error.Append("Error Compiling Expression: ");
  foreach (CompilerError err in cr.Errors)
    error.AppendFormat("{0}\n", err.ErrorText);
  throw new Exception("Error Compiling Expression: " + error.ToString());
Assembly a = cr.CompiledAssembly;
_Compiled = a.CreateInstance("ADOGuy._Evaluator");

When I call the _Compiled object, I use a MethodInfo object to Invoke the call and return the result to the user:

public object Evaluate(string name)
  MethodInfo mi = _Compiled.GetType().GetMethod(name);
  return mi.Invoke(_Compiled, null);


This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


About the Author

Shawn Wildermuth
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Renju Vinod9-May-13 3:14
professionalRenju Vinod9-May-13 3:14 
QuestionString Expression evaluation Pin
specialdreamsin14-Jun-12 0:27
memberspecialdreamsin14-Jun-12 0:27 
QuestionUsage of this code Pin
gonzalito_uy24-Apr-12 18:14
membergonzalito_uy24-Apr-12 18:14 
QuestionWhat about Double type ? Pin
Kronborn28-Mar-12 3:16
memberKronborn28-Mar-12 3:16 
What about Double type ? - Can't get it work (
Integer is always printed in output - digits after decimal point discarded always.
GeneralMy vote of 5 Pin
MohammadAmiry3-Nov-11 2:30
memberMohammadAmiry3-Nov-11 2:30 
GeneralMy vote of 5 Pin
Nagy Vilmos2-May-11 1:18
memberNagy Vilmos2-May-11 1:18 
GeneralMy vote of 5 Pin
Yvan Rodrigues28-Mar-11 11:47
memberYvan Rodrigues28-Mar-11 11:47 
GeneralMy vote of 5 Pin
joyichantg21-Mar-11 21:30
memberjoyichantg21-Mar-11 21:30 
GeneralMy vote of 5 Pin
kaikg31-Aug-10 5:51
memberkaikg31-Aug-10 5:51 
GeneralGood job! Pin
kaikg31-Aug-10 5:51
memberkaikg31-Aug-10 5:51 
GeneralMy vote of 5 Pin
Igor Gresovnik16-Aug-10 12:58
memberIgor Gresovnik16-Aug-10 12:58 
GeneralThanks Pin
jigi_chavan13-Oct-09 2:02
memberjigi_chavan13-Oct-09 2:02 
Generalpls help Pin
Xandip30-Sep-09 5:50
memberXandip30-Sep-09 5:50 
Generalgreat tool! Pin
abomb2229-May-09 6:10
memberabomb2229-May-09 6:10 
RantDownload link is not working Pin
parslej27-Mar-09 5:58
memberparslej27-Mar-09 5:58 
GeneralBoolean expression evaluator Pin
jackietrillo17-Feb-09 18:22
memberjackietrillo17-Feb-09 18:22 
AnswerRe: Boolean expression evaluator Pin
Member 378665520-Feb-09 11:37
memberMember 378665520-Feb-09 11:37 
QuestionLicence ? Pin
asalmi16-Sep-08 7:12
memberasalmi16-Sep-08 7:12 
AnswerRe: Licence ? Pin
gonzalito_uy11-Feb-10 7:19
membergonzalito_uy11-Feb-10 7:19 
Questiondoes it evaluate the expression ? Pin
Paresh Gheewala7-Aug-08 22:21
memberParesh Gheewala7-Aug-08 22:21 
GeneralGarbage Collection Pin
TGKelley14-Aug-07 16:25
memberTGKelley14-Aug-07 16:25 
Questioncan a web project use "ReferencedAssemblies.Add("customer.dll")" Pin
wlbkeats8-Dec-06 0:34
memberwlbkeats8-Dec-06 0:34 
GeneralEval custom classes Pin
Pluisjeh15-Mar-06 1:41
memberPluisjeh15-Mar-06 1:41 
GeneralEval Objects Pin
ZiggY816-Mar-06 4:52
memberZiggY816-Mar-06 4:52 
GeneralIt's Great! Pin
James Yang20-Feb-06 4:16
memberJames Yang20-Feb-06 4:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180111.1 | Last Updated 21 Apr 2002
Article Copyright 2002 by Shawn Wildermuth
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid