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.

Anton Semenov
  • 6,227
  • 5
  • 41
  • 69
tpascale
  • 2,516
  • 5
  • 25
  • 38
  • 1
    Have you seen Dynamic LINQ? http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx – Gabe Mar 23 '11 at 13:33
  • see: http://stackoverflow.com/questions/2965597/net-4-run-code-from-string-in-c-f-ironruby-ironpython – RBZ Mar 23 '11 at 14:47

5 Answers5

1

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

Zebi
  • 8,682
  • 1
  • 36
  • 42
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.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
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.

Tony Kh
  • 1,512
  • 11
  • 8
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

Anton Semenov
  • 6,227
  • 5
  • 41
  • 69
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. :-)

Patrick Huizinga
  • 1,342
  • 11
  • 25