Sometimes in the life of a C# programmer, you may want to evaluate a non-hard-coded expression in C#. There are several ways to do this:
- Use Flee (Fast Lightweight Expression Evaluator)
- Write your own expression parser with or without the help of existing tools and/or libraries
- Generate C# code on the fly, compile it at runtime and use it through Reflection
- The solution described in this article
eval() method. This is a very simple method but it can support many different scenarios. For example, it can be used to evaluate mathematical expressions as well as boolean expression. It can also be used to process or generate strings.
The idea of this article is not unique. I found references to this idea in several user groups. However, I couldn't find an article describing it step by step.
Please note that this method may not be very secure. I recommend to use it only if the expressions being evaluated are somewhat controlled and not directly entered by just any user.
Using the Code
public function Eval(expr : String) : String
return eval(expr, "unsafe");
CompileEvaluator.bat contains the command for compiling the .js file into a .NET assembly named "MB.JsEvaluator.dll". The batch file must be run from the Visual Studio command prompt. The source code already contains a copy of this assembly, so you don't have to do this.
REM Run from Visual Studio prompt.
jsc /target:library MB.JsEvaluator.js
Using the MB.JsEvaluator Assembly
In your project, you must reference both "MB.JsEvaluator.dll" and "Microsoft.JScript". The code below shows the meat of the very simple demo application:
Console.WriteLine("Enter an expression:");
string expression = Console.ReadLine();
MB.JsEvaluator.Evaluator evaluator = new MB.JsEvaluator.Evaluator();
string result = evaluator.Eval(expression);
How I Used This
I think Flee could also have been a viable option, but I didn't know about it during that time.
- 5 Dec 2009 - Initial version