C# Eval - Compile Method - The delegate / parameter type

CSharp · Console

/Program.cs

// C# Eval Expression
// Doc: https://eval-expression.net/eval-compile

// @nuget: Z.Expressions.Eval

/*
### The delegate / parameter type

The delegate is the method signature representing what parameter is allowed and the returned type. A delegate is either a `Func` when returning a value or an `Action` when there is no return.

For example, `Func<string, int, double>` is similar to `public double MyMethodName(int, double)`. If you don't wish to return a type, you must use an Action such as `Action<string, int>` is similar to `public void MyMethodName(int, double)`.

Most of the time, you will want to specify the delegate yourselves, but this is optional as we can create one for you depending on the list of types you specified or how you pass the parameter names.

For example, if you don't specify a delegate but specify 2 types, such as `Compile(code, int, int)`, we will create a `Func<int, int, object>` delegate. Also, if you don't specify a delegate, you will need to use position in the expression, such as `{0}` corresponds to the first type, as there is currently no way to pass parameter names.

In the following example, you will find multiple uses of the delegate:

See more: https://eval-expression.net/eval-compile
*/

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

public class Program
{
	public static void Main()
	{
		// 1. Eval.Compile<Func<int, int, int, List<int>>>(code)
		{
			var compiledList1 = Eval.Compile<Func<int, int, int, List<int>>>("var list = new List<int>(); list.Add({0}); list.Add({1}); list.Add({2}); return list;");
			
			var list1 = compiledList1(2, 4, 6);
		
			FiddleHelper.WriteTable(list1);
		}

		
		// 2. Eval.Compile(code, typeof(int), typeof(int), typeof(int));
		{
			var compiledList2 = Eval.Compile("var list = new List<int>(); list.Add({0}); list.Add({1}); list.Add({2}); return list;", typeof(int), typeof(int), typeof(int));
			
			var list2 = (List<int>)compiledList2(3, 5, 7);
		
			FiddleHelper.WriteTable(list2);
		}
		
		// 3. Eval.Compile<Action<List<int>>>(code);
		{
			var list3 = new List<int>();
			var compiledAction = Eval.Compile<Action<List<int>>>("{0}.Add(4);{0}.Add(6);{0}.Add(8);");
			compiledAction(list3);
			
			FiddleHelper.WriteTable(list3);
		}
	}
}

;