Click here to Skip to main content
Click here to Skip to main content

Evaluate C# Code (Eval Function)

, 12 Oct 2005 CPOL
Rate this:
Please Sign up or sign in to vote.
An example that provides an Eval function for compiling/evaluating C# code at runtime.

Sample Image - EvalCSCode.jpg

Introduction

This example shows an "Eval" function for C# and implements different usages of this evaluate function. The library is written in C# and can be tested with the MainForm in the solution.

Source view

Here you will see all the trick. The code generates a class structure with a basic "function prototype" in which the code to evaluate is filled in. The execution of the function should execute your code:

// Eval > Evaluates C# sourcelanguage
public static object Eval(string sCSCode) {

  CSharpCodeProvider c = new CSharpCodeProvider();
  ICodeCompiler icc = c.CreateCompiler();
  CompilerParameters cp = new CompilerParameters();

  cp.ReferencedAssemblies.Add("system.dll");
  cp.ReferencedAssemblies.Add("system.xml.dll");
  cp.ReferencedAssemblies.Add("system.data.dll");
  cp.ReferencedAssemblies.Add("system.windows.forms.dll");
  cp.ReferencedAssemblies.Add("system.drawing.dll");

  cp.CompilerOptions = "/t:library";
  cp.GenerateInMemory = true;

  StringBuilder sb = new StringBuilder("");
  sb.Append("using System;\n" );
  sb.Append("using System.Xml;\n");
  sb.Append("using System.Data;\n");
  sb.Append("using System.Data.SqlClient;\n");
  sb.Append("using System.Windows.Forms;\n");
  sb.Append("using System.Drawing;\n");

  sb.Append("namespace CSCodeEvaler{ \n");
  sb.Append("public class CSCodeEvaler{ \n");
  sb.Append("public object EvalCode(){\n");
  sb.Append("return "+sCSCode+"; \n");
  sb.Append("} \n");
  sb.Append("} \n");
  sb.Append("}\n");

  CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());
  if( cr.Errors.Count > 0 ){
      MessageBox.Show("ERROR: " + cr.Errors[0].ErrorText, 
         "Error evaluating cs code", MessageBoxButtons.OK, 
         MessageBoxIcon.Error );
      return null;
  }

  System.Reflection.Assembly a = cr.CompiledAssembly;
  object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");

  Type t = o.GetType();
  MethodInfo mi = t.GetMethod("EvalCode");

  object s = mi.Invoke(o, null);
  return s;

}

Thanks fly out to:

Credits:

  • Kim Hauser (dave) - Application Developer & System Engineer.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

kim.david.hauser
Software Developer (Senior)
Switzerland Switzerland
programmer and software junkie since 1991 zurich switzerland
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionEval LINQ expersion PinmemberFarazLoloei25-Oct-14 4:02 
QuestionGood work PinmemberSm.Abdullah6-Oct-12 21:13 
QuestionHow do you replace a string at a given position with it's working code representative? PinmemberLarissa Schön17-Mar-12 1:47 
GeneralAwesome, though quick question Pinmembermbainrot10-Apr-09 22:03 
QuestionEvalToObject Question Pinmembergravelkm14-Nov-08 3:43 
Hi Mark (and others),
 
I noticed your past on CodeProject.com regarding the code that can be used to create an "Eval"-type function in C#. I'm trying to utilize the "EvalToObject" method in that I want to convert a statement similar to:
 
document.Reports.Add(new EandG_MonthlyReport(document));
 
where the class name "EandG_MonthReport" is a string variable.
 
How would I set this up?
 
I've tried code similar to:
 
object o = Evaluator.EvalToObject("document.Reports.Add(new " + WebReport.PDFReportAppClassName.ToString() + "(document))");
 
where "WebReport.PDFReportAppClassName.ToString() " is the name of the class I want to instantiate, but I get errors stating " variable is not defined."
 
Your help is greatly appreciated!
 
Thank you,
Kevin Gravelle

Questioncan a web project use "ReferencedAssemblies.Add("customer.dll")" Pinmemberwlbkeats8-Dec-06 0:34 
AnswerRe: can a web project use "ReferencedAssemblies.Add("customer.dll")" Pinmemberlzuxiaolong27-Nov-12 16:13 
GeneralUses of Eval PinmemberAnup Shinde29-Sep-06 17:06 
GeneralTotal waste of time... Pinmembermarkman@shaw.ca3-Mar-06 13:08 
GeneralRe: Total waste of time... PinmemberPascal Ganaye20-Mar-06 10:12 
GeneralRe: Total waste of time... Pinmembermarkman@shaw.ca21-Mar-06 6:54 
GeneralRe: Total waste of time... PinmemberGraham Harrison12-Jan-07 0:34 
GeneralAn Eval Function for C# using JScript.NET (JavaScript) PinmemberMichael Freidgeim5-Jan-11 1:48 
GeneralRe: Total waste of time... Pinmemberkim.hauser8-Feb-07 3:37 
GeneralRe: Total waste of time... Pinmembermarketware30-Aug-07 12:25 
GeneralRe: Total waste of time... Pinmembermarketware31-Aug-07 12:08 
GeneralI dont think Total waste of time.. PinmemberMidax27-Apr-10 10:40 
QuestionUses PinmemberEvilToilet23-Oct-05 10:15 
AnswerRe: Uses Pinmemberkim.hauser2-Nov-05 12:03 
GeneralThanks for review... Pinmemberkim.hauser21-Oct-05 11:13 
QuestionUsing a static method instead Pinmemberanonymous19-Oct-05 21:07 
AnswerRe: Using a static method instead Pinmemberaprenot21-Oct-05 11:17 
GeneralRe: Using a static method instead PinmemberToli Cuturicu20-Dec-10 12:22 
GeneralExcellent! But Pinmembercccccbbbbb19-Oct-05 15:41 
GeneralRe: Excellent! But Pinmemberkim.hauser22-Oct-05 1:29 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411022.1 | Last Updated 13 Oct 2005
Article Copyright 2005 by kim.david.hauser
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid