Context

To use data in an expression, the data has to be passed in a ParserContext object. The context object is essentially a dictionary of key-value pairs. The keys are the variables that will be available in the expression.

For example:

var parser = new CSharpParser();
var context = new ParserContext();

context["x"] = 10;
context["y"] = 5;

var result = parser.Evaluate<int>("x+y", context); // returns 15

By default, the ParserContext uses strict C# rules for evaluating expression. This means that variables are case sensitive and non-boolean expressions can't be used as booleans. The context can be configured to be more relaxed by specifying a ParserContextBehavior enum parameter.

ParserContextBehavior has the following flags:

Rules for converting an expression to a boolean:

Flag
NullIsFalse null is treated as false
NotNullIsTrue not null is treated as true
NotZeroIsTrue any numeric value which is not zero is treated as true
ZeroIsFalse any numeric value which is zero is treated as false
EmptyStringIsFalse an empty string is treated as false
NonEmptyStringIsTrue a non-empty string is treated as true
EmptyCollectionIsFalse an empty collection is treated as false

Other flags:

Flag
ReturnNullWhenNullReference Expression returns null when a null value is dereferenced
CaseInsensitiveVariables Variable names are case insensitive

Combinations

Flag
Falsy NullIsFalse | NotNullIsTrue | NotZeroIsTrue | ZeroIsFalse | EmptyStringIsFalse | NonEmptyStringIsTrue | EmptyCollectionIsFalse
Easy Falsy | ReturnNullWhenNullReference

FlexContext

It's very common to use the most relaxed evaluation rules for expressions. The FlexContext class is a subclass of ParserContext with a default behavior of Easy, which means that any expression is convertible to a boolean and any null references in an expression will result in null to be returned instead of throwing an exception.