Editorials

Formula Evaluation in C#

C# does not have a method evaluate the results of a mathematical expression contained in a string. If it did, it would be similar to evaluating a formula you might enter in a cell in a spreadsheet. When the contents of the cell are evaluated, the contents are translated into a series of math variables and operations that can be executed, and the results returned.

I looked for a method to perform this kind of evaluation and found a popular way to perform this kind of runtime expression evaluation was to build IL code at runtime and load the code dynamically at runtime. While this is readily done, it does take a little work to create the new code and instantiate it in it’s own app pool so that the code can be removed from memory without stopping the app.

I did some further research recently to find out if there is a dot net equivalent posting by an enterprising developer. I found a number of different implementations and came across a hint on how it can be done.

If the formula is converted into postfix notation (often referred to as polish notation) the contents of the expression can be converted to a list of values, and sequentially, regardless of the order of operations (Multiply and Divide are calculated before Plus and Minus).

10 + 2 * 20 / 40 would be translated to 2 * 20 / 40 + 10 based on the order of operations.

In postfix notation it would look like 10 2 20 * 40 / +

The polish notation string is processed from left to right. Each item is placed on a stack until an Operand is found. The last two variables are popped off the stack, the operation is performed, and the result is placed back on the stack. This process continues until no more Operands are found. The execution completes with only one value on the stack, the final result.

Initial
List
First
Operation
Second
Operation
Last
Operation
10
2
20
*
40
/
+
10

40
40
/
+

10

1
+

11

Using traditional data structures such as a list and a stack you are able to compute the results of a string formula in postfix notation with little difficulty.

The hardest part is to translate an infix expression (how we write formulas naturally) into a postfix expression. This translation needs to take into account order of operations as well as overriding the order of operations by enclosing portions of the formula in parentheses.

Do you have a method for evaluating formulas you like to use in Dot Net? Perhaps a third party tool or control? Share your Eval tip in comments here or by email to btaylor@sswug.org.

Cheers,

Ben