CSharp · Console
// C# Eval Expression
// Doc: https://eval-expression.net/eval-compile
// @nuget: Z.Expressions.Eval
/*
## Compile Async
The C# Eval library doesn't have `CompileAsync` methods. Under the hood, we compile the expression which the [Expression<TDelegate>.Compile method](https://learn.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression-1.compile), which doesn't have a `CompileAsync` method either.
However, the `Compile` method support `Async` expression, but the task needs to be handled on the [Execute](/eval-execute#execute-async) part and not the compile part:
1. **Return a task from the delegate:** `Eval.Compile<Func<Task>>(code)`
2. **Handle the task** using `await` in the code
1 - If you **return a task from the delegate** (`Eval.Compile<Func<Task>>(code)`), you need to handle the task with `await` outside the code you want to compile and execute dynamically:
2 - If you **handle the task**, you need to use `await` inside the code you want to compile and execute dynamically:
See more: https://eval-expression.net/eval-compile
*/
using System;
using System.IO;
using System.Threading.Tasks;
using Z.Expressions;
public class Program
{
public static async Task Main()
{
var fileName = "myfile.txt";
await File.WriteAllTextAsync(fileName, "C# Eval Expression from ZZZ Projects");
// 1. **Return a task from the delegate:** `Eval.Compile<Func<Task>>(code)`
{
var compiled1 = Eval.Compile<Func<string, Task<string>>>("File.ReadAllTextAsync(fileName)", "fileName");
var text1 = await compiled1(fileName);
Console.WriteLine(text1);
}
// 2. **Handle the task** using `await` in the code
{
var compiled2 = Eval.Compile<Func<string, string>>("await File.ReadAllTextAsync(fileName)", "fileName");
var text2 = compiled2(fileName);
Console.WriteLine(text2);
}
}
}