tpascale
tpascale

Reputation: 2576

C# - can I define a function on the fly from a user-supplied string formula?

I can define a func with a lambda expression as in:

Func <int, int, int> Fxy = ( (a,b) => a + b ) );  // Fxy does addition

But what if I wanted to allow the user to supply the r.h.s. of the lambda expression at runtime ?

String formula_rhs = Console.Readline();
// user enters "a - b"

Can I somehow modify Fxy as if I had coded

Func <int, int, int> Fxy = ( (a,b) => a - b ) );  // Fxy does what the user wants 
                                                  // (subtraction)

I presently use a home built expression parser to accept user-defined formulas. Just starting up w .NET, and I get the feeling there may be a not-too-painful way to do this.

Upvotes: 2

Views: 1318

Answers (5)

Patrick Huizinga
Patrick Huizinga

Reputation: 1340

Using Linq.Expressions could be an idea here.

Your example would tranlate to:

var a = Expression.Parameter(typeof(int), "a");
var b = Expression.Parameter(typeof(int), "b");
var sum = Expression.Subtract(a, b);
var lamb = Expression.Lambda<Func<int, int, int>>(sum, a, b);
Func<int, int, int> Fxy = lamb.Compile();

Ofcourse, you will have the fun of parsing a string into the correct expressions. :-)

Upvotes: 0

Anton Semenov
Anton Semenov

Reputation: 6347

If you are planning to use not complex formulas, JScript engine would easy solution:

        Microsoft.JScript.Vsa.VsaEngine engine = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
        MessageBox.Show(Microsoft.JScript.Eval.JScriptEvaluate("((2+3)*5)/2", engine).ToString());

Dont forget to add reference to Microsoft.JScript assembly

Upvotes: 0

Tony Kh
Tony Kh

Reputation: 1572

System.Reflection.Emit namespace is intended for code generation on-the-fly. It is quite complicated in general but may help for simple functions like subtraction.

Upvotes: 0

Zebi
Zebi

Reputation: 8882

Try the ncalc framework: http://ncalc.codeplex.com/ Its easy and lightweight.

Upvotes: 1

Felice Pollano
Felice Pollano

Reputation: 33272

Is not so easy. This library contains some Dynamic Linq features you can use to convert a lambda expression from text to Func<>, have a look at it.

Upvotes: 0

Related Questions