C# Eval - Execute Method - The parameters - `Eval.Execute<TResult>(string code, params object[] parameters)`

CSharp · Console

/Program.cs

// 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

---

3 - In the case of `Eval.Execute<TResult>(string code, params object[] parameters)`, you can pass your parameter through the `params object[]`. You can learn more about [params here](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params)

3a - Since parameters are not named (our library doesn't know your variable, property, or field name), you need to use positions such as `{0}` and `{1}` in the expression as you usually do with, for example, [string.Format](https://learn.microsoft.com/en-us/dotnet/api/system.string.format):

3b - In addition, unlike section 2 (`Eval.Execute<TResult>(string code, object parameters)`) that we have seen, you cannot use member names or key names directly by default unless you use the [IncludeMemberFromAllParameters option](/options#includememberfromallparameters)
   
See more: https://eval-expression.net/eval-execute
*/

using System;
using System.Collections.Generic;
using Z.Expressions;

public class Program
{
	public static void Main()
	{
		// example 3a
		{
			var expression = "return new List<int>() { 1, 2, 3, 4, 5 }.Where(x => x > {0} && x < {1})";
			var list3a = Eval.Execute<List<int>>(expression, 1, 5);

			FiddleHelper.WriteTable(list3a);
		}
		
		// example 3b
		{
			var context = new EvalContext();

			// SET IncludeMemberFromAllParameters option
			context.IncludeMemberFromAllParameters = true;

			var parameter1 = new Parameter1() { MinValue = 1 };
			var parameter2 = new Parameter2() { MaxValue = 5 };

			var expression = "return new List<int>() { 1, 2, 3, 4, 5 }.Where(x => x > MinValue && x < MaxValue)";
			var list3b = context.Execute<List<int>>(expression, parameter1, parameter2);

			FiddleHelper.WriteTable(list3b);
		}
	}
	
	public class Parameter1
	{
		public int MinValue { get; set; }
	}
	
	public class Parameter2
	{
		public int MaxValue { get; set; }
	}
}

;