I'm looking for a language that will parse mathematical expressions for me pretty easily, but also be able to call functions and reference variables as needed. Jeval looks to be what I'm looking for, but unfortunately I'm working in C#. Is there a .Net based equivalent to jeval?
In C# 4.0, there is nothing directly available to you. It is expected that in C# 5.0, you will see it, but that doesn't help you now.
There is an alternative... you can use the Code DOM to compile some code on the fly, and then run it: Quick example.
There are, unfortunately, some significant downsides to this approach. First, it is slow. On a modern machine, it can take as long as a quarter of a second, just to compile the smallest code snippet. Second, you are actually creating a new DLL that gets loaded up every time you do this. If you have a system that likes run dynamic code a lot, you will have a ton of dynamically generated DLLs in your working space. To fix that, you can execute the dynamic code in a separate App Domain, but now you are starting to get really complicated.
My recommendation: Use an embedded scripting language, like IronRuby and generate Ruby code instead. You can eval embedded scripting languages significantly quicker than the approach I just outlined.
You can use a DLR language like IronRuby to do this. You can execute (eval) a script file from within a C# application.
You can do this with reflection. I don't have the details with me, but I have used reflection to execute a string that contained the name of an object I wanted to use.
If JavaScript sounds appealing to you, take a look at Jint, a JS interpreter for .NET. Instead of compiling code and dealing with AppDomains, Jint actually implements a JS interpreter. You can expose variables/methods from your .NET classes to scripts, and scripts can return values to your C# app.
Definitely worth checking out.
There's an easy way to do it, using the JScript eval
function :
create a JScript source file, JsMath.js :
class JsMath { static function Eval(expression : String) : double { return eval(expression); }; }
compile it to a DLL :
> jsc /t:library JsMath.js
in your C# project, add a reference to JsMath.dll, and call the
JsMath.Eval
method :double x = JsMath.Eval("2 + 3 * 4");