Injecting functions

User-defined functions can be injected in the expression evaluator. This allows custom code to be executed inside an expression.

For example, if you have a function that retrieves a stock quote, you can evaluate an expression that uses this function:

"NumShares * StockQuote(Symbol)"

This will return a portfolio value for a specific stock.

There are 2 ways to add a function to the context of an expression:

  • delegates
  • static / instance methods

Delegate / Lambda

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

context["NumShares"] = 500;
context["Symbol"] = "MSFT";
context["StockQuote"] = new Func<string,decimal>(symbol => stockService.GetQuote(symbol).Price);

var value = parser.Evaluate<decimal>("NumShares * StockQuote(Symbol)");