-1

To make it short what I want to do is convert a simple string like "/" into the actual / symbol so I can use it like this.

The button.Text in the code below will be one of these "+" , "-", "/", "*"

Button button = (Button)sender;

lblAns.Text = (Convert.ToDouble(txtNum1.Text) + button.Text + Convert.ToDouble(txtNum2.Text)).ToString();

I hope this makes sense...

Thanks ahead.

Zein Makki
  • 29,485
  • 6
  • 52
  • 63
ian korkie
  • 53
  • 1
  • 8
  • Well what's wrong? – rory.ap Jul 07 '16 at 20:34
  • 1
    you can't do that. you need to parse the string, and if you see `/`, you'll know you need to divide. You can't just convert the string into code (I know, you really can, but you don't want to) – Jonesopolis Jul 07 '16 at 20:37
  • 1
    Oh haha, I was assuming he wanted to display the formula on the label, not the actual mathematical result! No, this is torturing all good coding principals in many ways. – rory.ap Jul 07 '16 at 20:38
  • haha, yes i know its not the normal way of doing it but i like to find new an unique ways of doing things, if i can get that code to work it will replace 13 other lines of code. So i would prefer to use only 2 instead of 13. – ian korkie Jul 07 '16 at 20:44
  • @iankorkie -- You will learn as you build experience that shorter is not *always* better. There are tried and true principals to the art of software development, many of which you're breaking by applying your shortcuts. – rory.ap Jul 07 '16 at 20:46
  • @iankorkie check my answer below, you can do it using strings only as you want. – Zein Makki Jul 07 '16 at 20:48
  • @Jonesopolis Actually he can check my answer below. – Zein Makki Jul 07 '16 at 20:51
  • @iankorkie please edit your post to provide expected result and concrete criteria for acceptable answer. So far you just comment "I don't like you suggestion" - this is not a way to create Q/A pairs on SO. Also make sure to clarify how it is different from usual http://stackoverflow.com/questions/5838918/evaluate-c-sharp-string-with-math-operators – Alexei Levenkov Jul 07 '16 at 21:00
  • Thanks all for the advice, I will take it all in account in the future ; ) – ian korkie Jul 07 '16 at 21:16

1 Answers1

0

It turns out you can actually do that this way:

Compute a Mathematical Operation using Strings Only in C#

string statement = txtNum1.Text + button.Text + txtNum2.Text;
lblAns.Text = new System.Data.DataTable().Compute(statement, "").ToString();

Working Example.

string result = (new System.Data.DataTable()).Compute("5 * 4 + 1", "").ToString();
Console.WriteLine(result); // prints 21
Zein Makki
  • 29,485
  • 6
  • 52
  • 63