Skip to content
Shaun Lawrence edited this page Aug 27, 2019 · 7 revisions

Simple Evaluation

var expression = new Expression("1+2");
var result = expression.Evaluate();

Custom options

public enum ExpressiveOptions
{
    /// <summary>
    /// Specifies that no options are set.
    /// </summary>
    None = 1,
    /// <summary>
    /// Specifies case-insensitive matching.
    /// </summary>
    IgnoreCase = 2,
    /// <summary>
    /// No-cache mode. Ignores any pre-compiled expression in the cache.
    /// </summary>
    NoCache = 4,
    /// <summary>
    /// When using Round(), if a number is halfway between two others, it is rounded toward the nearest number that is away from zero.
    /// </summary>
    RoundAwayFromZero = 8,
    /// <summary>
    /// All options are used.
    /// </summary>
    All = IgnoreCase | NoCache | RoundAwayFromZero,
}

// Use in any combination.
var expression = new Expression("1+2", ExpressiveOptions.IgnoreCase | ExpressiveOptions.NoCache);
var result = expression.Evaluate();

Variables

var expression = new Expression("1 * [variable]");
var result = expression.Evaluate(new Dictionary<string, object> { ["variable"] = 2);

Built-in Functions

Expressive provides a standard set of functions (see Functions).

var expression = new Expression("sum(1,2,3,4)");
var result = expression.Evaluate();

Custom Functions

Custom functions allow you to register your own set of functionality in order to extend the current set. There are 2 methods of registering a custom function:

  • IFunction implementation.
internal class AbsFunction : IFunction
{
    #region IFunction Members

    public IDictionary<string, object> Variables { get; set; }

    public string Name { get { return "Asin"; } }

    public object Evaluate(IExpression[] parameters)
    {
        return Math.Asin(Convert.ToDouble(parameters[0].Evaluate(Variables)));
    }

    #endregion
}

var expression = new Expression("Abs(1)");
expression.RegisterFunction(new AbsFunction());
var result = expression.Evaluate();
  • Lambda callback.
var expression = new Expression("myfunc(1)");
expression.RegisterFunction("myfunc", (p, v) =>
{
    // p = parameters
    // v = variables
    return p[0].Evaluate(v);
});
var result = expression.Evaluate();

Retrieve referenced variables

Compiles the expression and returns an array of the variable names contained within the expression.

var expression = new Expression("[abc] + [def] * [ghi]");
var variables = expression.ReferencedVariables;

Asynchronous evaluation

Useful for when an evaluation might take a long time (i.e. a function that deals with a long running background tasks such as loading from the database).

var expression = new Expression("1+2");
expression.EvaluateAsync((r) =>
{
    var result = r;
});