CSharp · Console
// C# Eval Expression
// Doc: https://eval-expression.net/my-first-evaluation
// @nuget: Z.Expressions.Eval
/*
## Use Option for Safe Mode
The [Safe Mode](/options#safemode) ensures that only members and types registered can be used for the expression.
To use safe mode, we recommend:
- A local or static context
- Unregistering all types first
- Limiting the maximum number of loops with the [MaxLoopIteration](/options#maxloopiteration) option
- Setting the `SafeMode` option to true
- Registering only what you want the user to be able to use
For example, we will demonstrate how easy it is to configure options in the C# Eval Expression library:
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()
{
var evalContext = new EvalContext();
evalContext.UnregisterAll();
evalContext.MaxLoopIteration = 5;
evalContext.SafeMode = true;
evalContext.RegisterMember(typeof(System.Math));
var r1 = evalContext.Execute("Math.Min(1, 2)");
Console.WriteLine("1 - Result: " + r1);
try
{
// `List` is no longer registered, so it cannot be used
var r2 = evalContext.Execute("new List<int>()");
}
catch(Exception ex)
{
Console.WriteLine("Cannot use `List` exception: " + ex.Message);
}
}
}