CSharp · Console
// C# Eval Expression
// Doc: https://eval-expression.net/eval-execute
// @nuget: Z.Expressions.Eval
/*
## Execute Async
The C# Eval library supports `Async` but has no `ExecuteAsync` method.
Adding `Async` methods doesn't make sense, as your non-async code will not magically start to be executed asynchronously. A code runs asynchronously when you call a method that supports async and returns a `Task` or `Task<TResult>`.
To execute `Async`, you have 2 choices:
1. **Return a task:** `Eval.Execute<Task>(code)` or `Eval.Execute<Task<Result>>(code)`
2. **Handle the task** using `await` in the code
1 - If you **return a task** (`Eval.Execute<Task>(code)` or `Eval.Execute<Task<Result>>(code)`), you need to handle the task with `await` outside the code you want to execute dynamically
2 - If you **handle the task**, you need to use `await` inside the code you want to execute dynamically
See more: https://eval-expression.net/eval-execute
*/
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:** `Eval.Execute<Task>(code)` or `Eval.Execute<Task<Result>>(code)`
{
var task = Eval.Execute<Task<string>>("File.ReadAllTextAsync(fileName)", new { fileName });
var text1 = await task;
Console.WriteLine(text1);
}
// 2. **Handle the task** using `await` in the code
{
var text2 = Eval.Execute<string>("await File.ReadAllTextAsync(fileName)", new { fileName });
Console.WriteLine(text2);
}
}
}