This project has moved and is read-only. For the latest updates, please go here.


I was working on rewriting an application that had very specific use into .NET and currently had one simple branching point: for a certain value a part of code should get executed. Everything was very much hard coded, but the client was expanding ,and I wanted to create a configuration file that could cater for future expansion.

I wanted to be able to define a condition "x == c" where x was a property of an runtime object that would vary over calls, and c was a constant. This condition should be defined in an XML file where it could be changed if needed. I also wanted to ensure that any further conditions could also be defined in this manner, without the need to write any code.

That got me thinking: did C# have some way to evaluate a string as an expression during runtime, like VBScript's Eval()? It turns out, it did not.

One of the options I found around the internet was to create a complete class, compile the code into an assembly, load it into memory and call the function through reflection, but I immediately rejected this solution as it was clunky and inelegant, and a lot of work for a check if "x == c".

I then came across Pascal Ganaye's Eval3 library. The library supported passing external variables through a class - just what I needed. It performed well enough (I had to modify the existing code to accommodate the equals operator) but I felt that it was a bit difficult to maintain (had to write a function for each operator-combination type) and I was trying to move away from VB.NET.

I had been exposed to LINQ and Expression trees through my AccessToLINQ project and I realized that Expression trees could be compiled into functions, and all I needed was some sort of parser to build an expression tree from a string expression.

With a bit of help from Wikipedia, I borrowed an implementation of Dijkstra's Shunting-yard algorithm (NOTE: unfortunately the code sample has been removed, see the history to view the sample code) to handle the parsing, rewrote it in C#, threw in Expressions and had the evaluator up and running.

Last edited May 5, 2014 at 9:33 AM by RupertAvery, version 1


No comments yet.