Over the years, on the forums I frequent, the question has come up from time-to-time on how to dynamically evaluate expressions built at runtime. Often, the suggestions range from dynamic code compilation to creating expression evaluators. While these suggestions are not necessarily bad – they do have some drawbacks.
The main problem with dynamic code compilation, is that it is slow. This may not be an issue if you are only going to do one or two calculations – but, if you need to perform your calculations hundreds or thousands of times, then the performance hit can become significant. For example, on the MSDN Visual C# forum, I was recently involved in a thread where the original poster was using dynamic compilation to evaluate expressions thousands of times and was looking for ways to speed up the process. I suggested he try the method I am about to present here, and his processing time dropped from the approximately 7 hours to 49 seconds. Not bad.
The other method, creating an expression evaluator, suffers from complexity. It isn’t an easy task. Of course, there are enough examples and pre-built libraries to perform this task that no one should have to write such a beast anymore (except maybe as an exercise). But, why hunt down a third party library, when Microsoft has given us a built in expression evaluator? Well, sort of.
The expression evaluation mechanism that I am referring to is the JScript Eval method. It seems that many do not realize that JScript is an official .NET language. I suspect that is because the IDE has no built in support for JScript.NET. Here is a method for creating a simple wrapper library to expose the JScript Eval method to your C# or VB program.
This example, is pretty simplistic – for example, the Calculate methods do not do any sort of checking to make sure that the expression passed is a valid mathematical expression. I used the System.String.Format method to illustrate one way of getting values into an expression to be evaluated. It should be noted that this method will not only evaluate mathematical expressions, but arbitrary JScript code. As long as you are using a version of .NET >= 1.1, then this shouldn’t be much of an issue because unless you pass the string “unsafe” to the optional second parameter of the JScript Eval method, then the code will run in a limited security context. If you decide to ever use the Eval method with the “unsafe” option, then you will want to make sure that all of your strings are obtained from a trusted source.