Introduction

The EvalContext allow specifying customer configuration for evaluating, compiling and executing C# code and expression at runtime.

Execute

Problem

You need to evaluate a dynamic C# code in an instance context.

Solution

Create a new instance of EvalContext and use Execute method:

  • Execute<TResult>(string code)
  • Execute<TResult>(string code, object parameters)
  • Execute<TResult>(string code, params object[] parameters)
  • Execute(string code)
  • Execute(string code, object parameters)
  • Execute(string code, params object[] parameters)

Example

// using Z.Expressions; // Don't forget to include this.

var context = new EvalContext();
// ... context options ...

string code = "Price * Quantity";
var price = context.Execute(code, orderItem);

Compile

Problem

You need to compile a dynamic C# code in an instance context.

Solution

Create a new instance of EvalContext and use Compile method:

  • Compile<TDelegate>(string code)
  • Compile<TDelegate>(string code, IEnumerable<string> parameterNames)
  • Compile<TDelegate>(string code, params string[] parameterNames)
  • Compile(string): Func<object>
  • Compile(string, Type type1): Func<object, object>
  • Compile(string, Type type1, … , Type type9): Func<object, … , object, object>
  • Compile(string, IEnumerable<Type>): Func<IEnumerable, object>
  • Compile(string, params Type[]): Func<IEnumerable, object>
  • Compile(string, IDictionary<string, Type>): Func<IDictionary, object>

Example

// using Z.Expressions; // Don't forget to include this.

var context = new EvalContext();
// ... context options ...

string code = "Price * Quantity";
var compiled = context.Compile>(code);

decimal totals = 0;
foreach(var item in list)
{
    totals += compiled(item);
}