Introduction

The Eval.Compile method allows to compile a C# expression dynamically at runtime and return a delegate (Func or Action).

Example

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

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

decimal totals = 0;
foreach(var order in orders)
{
    totals += compiled(order);
}

Use Compile over Execute when you need to run the expression multiple times.

Eval.Compile<TDelegate>

Problem

You need to compile a dynamic C# code and return a strongly typed delegate.

Solution

Use the generic Eval.Compile method:

  • Eval.Compile<TDelegate>(string code)
  • Eval.Compile<TDelegate>(string code, IEnumerable<string> parameterNames)
  • Eval.Compile<TDelegate>(string code, params string[] parameterNames)

Example

// Delegate Func
var compiled = Eval.Compile>("{0} + {1}");
int result = compiled(1, 2);

// Delegate Action
var compiled = Eval.Compile>("{0} + {1}");
compiled(1, 2);

// Named Parameter
var compiled = Eval.Compile>("X + Y", "X", "Y");
int result = compiled(1, 2);

Eval.Compile

Problem

You need to compile a dynamic C# code and return a delegate.

Solution

Use the Eval.Compile method:

  • Eval.Compile(string code): Func<object>
  • Eval.Compile(string code, Type type1): Func<object, object>
  • Eval.Compile(string code, Type type1, … , Type type9): Func<object, … , object, object>
  • Eval.Compile(string code, IEnumerable<Type> types): Func<IEnumerable, object>
  • Eval.Compile(string code, params Type[] types): Func<IEnumerable, object>
  • Eval.Compile(string code, IDictionary<string, Type> nameTypes): Func<IDictionary, object>

Example

// Overload: Up to 9 parameters can be used
var compiled = Eval.Compile("{0} + {1}", typeof(int), typeof(int));
object result = compiled(1, 2);

// Overload: params Type[]
var values = new List() {1, 2};
var types = values.Select(x => x.GetType()).ToArray();

var compiled = Eval.Compile("{0} + {1}", types);
var result = compiled(values);

// Overload: IDictionary
var values = new Dictionary {{"X", 1}, {"Y", 2}};
var types = values.ToDictionary(x => x.Key, x => x.Value.GetType());

var compiled = Eval.Compile("X + Y", types);
var result = compiled(values);