tags:

views:

73

answers:

5

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?

+2  A: 

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.

Brian Genisio
Iron Python's a good one, too. Especially if he already knows python.
marr75
That's a very dangerous approach... any valid code entered by the user could be compiled and executed, and you can't easily check that this code is safe.
Thomas Levesque
I'm considering the ironpython approach, I'm not too worried about people potentially modifying the script files. I'm more concerned about having something that can look syntactically fairly simple, but reference variables and functions easily
Calvin
+3  A: 

You can use a DLR language like IronRuby to do this. You can execute (eval) a script file from within a C# application.

Jordão
A: 

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.

MikeMalter
A: 

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.

josh3736
A: 

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");
    
Thomas Levesque