C# Eval - My First Option - Use option to add keyword

CSharp · Console

/Program.cs

// C# Eval Expression
// Doc: https://eval-expression.net/my-first-evaluation

// @nuget: Z.Expressions.Eval

/*
## Use Option to Add Keyword

In the C# Eval Expression library, you can add your own `keyword`. You cannot override existing keywords, but you can create new ones, such as `isin`, that will check if the current item is in the list.

In this example, we will create an extension method named `IsIn` that checks if an item is part of a list. Then, we will create the keyword `isin` that will be bound to this extension method and can be used directly in the expression:

See more: https://eval-expression.net/my-first-evaluation
*/

using System;
using System.Collections.Generic;
using Z.Expressions;

public class Program
{
	public static void Main()
	{
		EvalManager.DefaultContext.RegisterExtensionMethod(typeof(CustomExtensions));
		EvalManager.DefaultContext.RegisterKeyword("isin", "IsIn");
		
		var list = new List<int>() { 1, 2, 3 };
		
		Console.WriteLine(Eval.Execute("2 isin list", new { list }));
		Console.WriteLine(Eval.Execute("4 isin list", new { list }));
	}
}

public static class CustomExtensions
{
	public static bool IsIn<T>(this T x, List<T> list)
	{
		return list.Contains(x);
	}
}
;