0

I have a textbox where i want to read user-input mathematical functions( ex: Math.Sqrt(x) etc).

The code I've been using for console testing the function is

    static double f(double x)
    {
        double f;
        f = Math.Sqrt(x);
        return f;
    }

I'm not sure how to modify it: do I read the textbox contents in a string, and add that string as a second argument to the f function ( static double f(double x, string s)? what type of parsing should I apply to the string?

user573382
  • 343
  • 3
  • 10
  • 22

4 Answers4

5

There are several formula parsers out there that you can use.

Basically you need someone/something that evaluates your formula.

I'm using this one successfully in my own projects. It allows for calling it like

var ev = 
    new Eval3.Evaluator(
        Eval3.eParserSyntax.c,/*caseSensitive*/ 
        false);

MessageBox.Show(ev.Parse("1+2+3").value.ToString());

What I would not recommend to use is the dynamic compilation of C# code since it adds each compiled code to your application domain ("app domain") and there is no option to unload it again. (Correct me, if I'm wrong).

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 1
    thank you, dunno why I didn't think of searching for something like this. I'll give the parser a shot, thanks – user573382 May 08 '12 at 06:39
1

Another evaluator: http://csharp-eval.com/

David Brabant
  • 41,623
  • 16
  • 83
  • 111
0

If your interested in how to get the text from the textbox and do something with the value the following code will do that for you. If you want to enter a function in the textbox - sqrt(40) you should check this project: http://www.codeproject.com/Articles/23061/MathParser-Math-Formula-Parser

http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.aspx

static double f(Textbox tb)
{
    double f;
    double x = Double.Parse(tb.Text);
    f = Math.Sqrt(x);
    return f;
}
t3hn00b
  • 904
  • 5
  • 13
0

You can execute arbitrary code, but not easily. For general code you must create a wrapper class and insert the code into a function.

Take a look at http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/6a783cc4-bb54-4fec-b504-f9b1ed786b54/

felixgaal
  • 2,403
  • 15
  • 24