CSharp · Console
// C# Eval Expression
// Doc: https://eval-expression.net/eval-execute
// @nuget: Z.Expressions.Eval
/*
### The parameters
You have multiple different ways how you can pass your parameters. Furthermore, there is no best way to pass parameters as everything depends on your scenario and preference:
1. `Eval.Execute<TResult>(string code)`: https://dotnetfiddle.net/4vOu2H
2. `Eval.Execute<TResult>(string code, object parameters)`: https://dotnetfiddle.net/wdLPTE
3. `Eval.Execute<TResult>(string code, params object[] parameters)`: https://dotnetfiddle.net/Q0gWZ3
---
1 - In the case of `Eval.Execute<TResult>(string code)`, you cannot pass parameters directly, but you can always common technic such as string concatenation or [string interpolation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated):**
> NOTE: Be careful when using string concatenation (1b) and string interpolation (1c). In the same way, using this technique for SQL can lead to SQL Injection; using this technique with code can lead to Code Injection. So you should generally avoid this solution if you execute code from user input.
See more: https://eval-expression.net/eval-execute
*/
using System;
using System.Collections.Generic;
using Z.Expressions;
public class Program
{
public static void Main()
{
// - 1a. Hardcoding parameter value in the expression
{
var expression = "return new List<int>() { 1, 2, 3, 4, 5 }.Where(x => x > 1 && x < 5)";
var list1a = Eval.Execute<List<int>>(expression);
FiddleHelper.WriteTable("1a. Hardcoding parameter value in the expression", list1a);
}
// - 1b. Using string concatenation
{
var minValue = 1;
var maxValue = 5;
var expression = "return new List<int>() { 1, 2, 3, 4, 5 }.Where(x => x > "+ minValue +" && x < "+ maxValue +")";
var list1b = Eval.Execute<List<int>>(expression);
FiddleHelper.WriteTable("1b. Using string concatenation", list1b);
}
// - 1c. Using [string interpolation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated)
{
var minValue = 1;
var maxValue = 5;
var expression = $"return new List<int>() {{ 1, 2, 3, 4, 5 }}.Where(x => x > {minValue} && x < {maxValue})";
var list1c = Eval.Execute<List<int>>(expression);
FiddleHelper.WriteTable("1c. Using [string interpolation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated)", list1c);
}
}
}