CSharp · Console
// C# Eval Expression
// Doc: https://eval-expression.net/eval-execute
// @nuget: Z.Expressions.Eval
/*
### The code
You can provide the code to execute in 3 different ways:
1. **Instance method:** `context.Execute(code)`
2. **Static method:** `Eval.Execute(code)`
3. **Extension method:** `"code".Execute`
1 - In the case of the **instance method** (`context.Execute(code)`). First, you create a new instance of the [EvalContext](https://eval-expression.net/eval-context), and then you can use the `Execute` method from the context created:
2 - In the case of the **static method** (`Eval.Execute(code)`), you can directly call the static `Eval.Execute` method, which uses a global context under the hood.
3 - In the case of the **extension method** (`"code".Execute`), you can directly call the `Execute` method that extends the string type, which uses a global context under the hood.
One of the major differences is whether you want to create a new instance of the [EvalContext](https://eval-expression.net/eval-context) or use the global context (an instance stored in a static variable).
We explain the answer more detail in the [EvalContext](https://eval-expression.net/eval-context) documentation, but in short:
- If you need to customize the context for this specific evaluation, **you should** use an instance context
- If you don't need to customize the context for this specific evaluation, **you can** use the global context
See more: https://eval-expression.net/eval-execute
*/
using System;
using System.Collections.Generic;
using Z.Expressions;
public class Program
{
public static void Main()
{
// 1. **Instance method:** `context.Execute(code)`
{
// CREATE a new instance of EvalContext
var context = new EvalContext();
// USE the `Execute` method from the context created
var list1 = context.Execute<List<int>>("new List<int>() { 1, 2, 3 };");
FiddleHelper.WriteTable(list1);
}
// 2. **Static method:** `Eval.Execute(code)`
{
// CALL the static `Eval.Execute` method
var list2 = Eval.Execute<List<int>>("new List<int>() { 1, 2, 3 };");
FiddleHelper.WriteTable(list2);
}
// 3. **Extension method:** `"code".Execute`
{
// CALL the `Execute` method that extends the string type
var list3 = "new List<int>() { 1, 2, 3 };".Execute<List<int>>();
FiddleHelper.WriteTable(list3);
}
}
}