ExpressionParser

Description
The ExpressionParser is a simple parser that can parse a mathematical expression into a custom expression tree which can be used to evaluate the expression. It also allows to convert the tree into a delegate.

Usage
To use the parser you have to include the namespace:

To evaluate a single expression without any customisation you can use ExpressionParser.Eval which will return a double value. You could also use Expression.Parse which will return the expression tree as object. It can be used to evaluate the value or to build a delegate. Those two static method will create a temporary ExpressionParser. If you plan to parse mutilple expressions you should create a parser instance yourself and use it's EvaluateExpression or Evaluate method. EvaluateExpression returns an expression tree and Evaluate a double.

Additional Notes
Custom methods have to check the parameter count itself. The passed array will just contain the parameters passed in the expression. So watch out to not blindly access a certain index in the parameter list. The linq methods FirstOrDefault and ElementAtOrDefault are quite useful here. They would simply return "0" if the index doesn't exist.

Expression delegates perform quite well, however the first execution is significantly slower than the following (not sure why ^^ maybe due to caching).

When using ToDelegate or ToMultiResultDelegate you have to specify the actual parameters. The strings you pass to those methods equals the parameters your delegate will have. The delegate takes a params array of double values. If you pass not enough parameters it won't result in an error, but the missing parameters just will keep their last value. Additional parameters are simply ignored.

Since the expression tree is build with class instances and contains an internal state it's not really thread safe.

The parser uses a quite strict syntax. As mentioned earlier brackets must not be empty, so you can't use a custom method without a parameter. The "unary minus" has to be wrapped with brackets. The parser doesn't support things like: 5 * -4. This should be 5 * (-4)