2

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.

2

5 Answers 5

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

0

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

Comments

0

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. :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.