2

Possible Duplicate:
Best and shortest way to evaluate mathematical expressions

How to run a string formula at runtime with C#?

string formula = "10/2";
var result = Run(result);

thanks

Community
  • 1
  • 1
The Light
  • 26,341
  • 62
  • 176
  • 258

1 Answers1

0

Some sort of scripting engine would need to be loaded and then the string would be passed to the scripting engine to evaluate.

One would just need to know which scripting lanaguage use. Javascript, VbScript, Python, etc. Attached is a link to Iron Python and some code that shows how to use it. Using VS2010 .Net 4.

http://ironpython.net/

using IronPython.Hosting;
using IronPython.Runtime;

//Script Engine Reference
using Microsoft.Scripting.Hosting;
//Source Code Kind Reference
using Microsoft.Scripting;

//Iron Python Reference
using IronPython.Hosting;
using IronPython.Runtime;
//Source Execute
using Microsoft.CSharp;

            ScriptEngine engine = Python.CreateEngine();
            ScriptRuntime runtime = engine.Runtime;
            ScriptScope scope = runtime.CreateScope();

            //Simple Example

            string code = @"emp.Salary * 0.3";


            ScriptSource source =
              engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);


            var emp = new Employee { Id = 1000, Name = "Bernie", Salary = 1000 };


            scope.SetVariable("emp", emp);


            var res = (double)source.Execute(scope);

            MessageBox.Show(res.ToString());




 public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double Salary { get; set; }


    }
Jon Raynor
  • 3,804
  • 6
  • 29
  • 43
  • how would be its performance? the difference is negligible? – The Light Aug 12 '11 at 16:27
  • I haven't tested it, but I would say it would be negligible. Any scripting engine is going to be slower than doing an operation directly in code, but the loss in performance is due to the fact it is doing a dynamic evaluation. So, with flexibility comes a small performance penalty. – Jon Raynor Aug 12 '11 at 16:53