CSharp · Console
// C# Eval Expression
// Doc: https://eval-expression.net/my-first-option
// @nuget: Z.Expressions.Eval
/*
## Use Option to Add Method
In the C# Eval Expression library, you can add your own method.
If you can define the method in a non-dynamic way, you should always prefer to [register your method](/register-unregister) instead of creating it dynamically. Registered methods are faster and more secure.
In this first example, we’ll create a simple custom method called `MinPlusOne` that returns the minimum value between two numbers and adds one:
https://dotnetfiddle.net/4VXupA
In this second example, we go one step further. We’ll create a more advanced method dynamically, where the logic (formula) is provided by the user. This is useful when you want to inject a user-defined expression directly into a method.
https://dotnetfiddle.net/ZlZjx4
See more: https://eval-expression.net/my-first-option
*/
using System;
using System.Collections.Generic;
using Z.Expressions;
public class Program
{
public static void Main()
{
string userInputFormula = "A == B || A == -1 || B == -1";
var evalContext = new EvalContext();
evalContext.AddMethod($$"""public bool IsEqualsCustom(int A, int B) { return {{userInputFormula}}; }""");
Console.WriteLine(evalContext.Execute<bool>("IsEqualsCustom(1, 1)"));
Console.WriteLine(evalContext.Execute<bool>("IsEqualsCustom(1, 2)"));
Console.WriteLine(evalContext.Execute<bool>("IsEqualsCustom(1, -1)"));
}
}