// C# Eval Expression
// Doc: https://eval-expression.net/my-first-compilation
// @nuget: Z.Expressions.Eval
/*
## Compile a C# expression
Like the `Execute` method, the `Compile` method takes as the first parameter the expression to compile.
In this example, we will dynamically create a list of `int` and filter it using LINQ to return only items greater than 2. The expression will be compiled into a method and then executed. The `Func<List<int>>` return type will be explained in the next example.
## Compile a C# expression with return type
In the last example, we successfully compiled an expression, but what exactly was the `Func<List<int>>` for?
The `Func<List<int>>` means that the `Compile` method should create a method that takes no parameter and returns a `List<int>`. Usually, the `Compile` method takes either an `Action` or `Func`.
- An `Action` should be used when the method doesn't return any type (like when you create a `void` method).
- A `Func` should be used when the compiled method should return a specific type
If you don't know how an `Action` and `Func` work, you can learn more on Google.
We will re-use the same previous example as we now understand how you can specify a return type to the created method.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Z.Expressions;
public class Program
{
public static void Main()
// NOTE: The returned list contains "3" and "4"
var compiled = Eval.Compile<Func<List<int>>>(@"
var list = new List<int>() { 1, 2, 3, 4 };
return list.Where(x => x > 2).ToList();
");
var list = compiled();
FiddleHelper.WriteTable(list);
}