-2

I am trying to make something like this work.

string operator = "+";
int randomNumber = 1;
int randomNumber2=2;

if(randomNumber+operator+randomNumber2 == 3)

But can't seem to get it to work, I also tried to do a char with no luck either.

Hasan Patel
  • 412
  • 7
  • 19

3 Answers3

1

the example you shared is completely wrong, One suggest for your issue:

  public static int Operator(this string logic, int x, int y)
    {
        switch (logic)
        {
            case "+": return x + y;
            case "-": return x - y;
            // And add your own cases

            default: throw new Exception("invalid logic");
        }
    }
yuvalchen
  • 133
  • 3
1

Simply,

if (operator == '+') return randomNumber + randomNumber2;

With more operators

switch (operator)
{
    case '+': return randomNumber + randomNumber2;
    case '-': return randomNumber - randomNumber2;
    ...
}
Kit
  • 20,354
  • 4
  • 60
  • 103
0

I posted a class that will parse a full expression on Black Belt Coder. That code simply tokenizes the input text and constructs an infix express, which it then evaluates. It allows you to define your own functions and variables too. Would that work in your case?

Also, may I ask why you want this? I would consider putting it on NuGet if I thought there was any demand.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466