0

I have made a GUI calculator. So when someone presses a button the numbers and symbols are displayed in a label then when they press enter the computer captures the string and that is where i need some help. I know that in Python there is a eval statement that can be used is there something similar in C#.

Here is the code if that helps. specifically look at the method button_click

public class form1 : Form
{
    private Label lab;
    private Button button2;
    private Button button;
    private Button plus;
    private MathFunctions.MathParser calc;

    public static void Main()
    {
        Application.Run(new form1());
    }

    public form1()
    {
       // Initialize controls
       ...
    }

    private void button_Click(object sender,System.EventArgs e)
    {
        string answer = lab.Text;
    }

    private void button2_Click(object sender,System.EventArgs e)
    {
        lab.Text = lab.Text + "2";
    }

    private void button_plus(object sender,System.EventArgs e)
    {
        lab.Text = lab.Text + "+";
    }
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
user1108980
  • 43
  • 1
  • 7

2 Answers2

1

In C# you don't have eval. You can in principle generate code at runtime, compile it, make an assembly and then execute code or you could spit out a dynamic method by emitting IL but all of that is not very straight forward.

I'd recommend you to just parse the string using one of the well known methods and then create expression tree.

OR you can use the deprecated javascript engine only for parsing expressions .

See Best and shortest way to evaluate mathematical expressions

Community
  • 1
  • 1
Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131
0

Since you are familiar with python why not use it? Create IronPyton Script Engine object in you C# code. Here's a snippet:

string expression = lab.Text; // @"540 +  4 / 3" try to test

ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromString(expression, SourceCodeKind.Expression);

int result = source.Execute<int>();
Lukasz Madon
  • 14,664
  • 14
  • 64
  • 108