C# Eval Expression String Extensions Methods

Description

Extend the String class with methods to Execute & Compile C# expression.

Under the hood, string extensions use the default context to execute and compile expressions.

public static object Execute(this string code, params object[] parameters)
{
    return EvalManager.DefaultContext.Execute(code, parameters);
}

"string".Execute

Execute a C# expression. Extend the String class.

  • "string".Execute<TResult>()
  • "string".Execute<TResult>(object parameters)
  • "string".Execute<TResult>(params object[] parameters)
  • "string".Execute()
  • "string".Execute(object parameters)
  • "string".Execute(params object[] parameters)

Example

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

var result1 = "1+2".Execute<int>(); // return 3
var result2 = "X+Y".Execute(new { X = 1, Y = 2 }); // return 3

Try it online

"string".Compile

Compile a C# expression. Extend the String class.

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

Example

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

string s = "Price * Quantity";
var compiled = s.Compile<Func<OrderItem, decimal>>(code);

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

Last updated: 2024-03-22
Author:


Contents