Can I save an operator in a variable?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • BurnTard
    New Member
    • May 2007
    • 52

    Can I save an operator in a variable?

    I'm not quite sure if this should be in the asp.net, or possibly the c# forums...

    I'm writing an asp.net calculator application in C#, and at this point it would be very useful if I could somehow save an operator in a variable, and then be able to use it later on, like this:

    Let's say I have the integer session variables a=2 and b=4
    [CODE=C#]

    protected void button_add(obje ct sender, EventArgs e)
    {

    operatorvar opx=+;
    }
    protected void button_equals(o bject sender, EventArgs e)
    {

    int answer=a opx b;
    }
    [/CODE]

    I also want the operator to be in a session variable.
    Is this at all possible? I did some googling, but ended up coming back here.
  • Curtis Rutland
    Recognized Expert Specialist
    • Apr 2008
    • 3264

    #2
    What I'd do in that situation is write a method like this:
    Code:
    //i'm just doing this off the top of my head, haven't tested this code
    private double PerformOperation(double a, char op, double b)
    {
      double retVal = 0;
      switch(op)
      {
        case '+':
          retVal = a + b;
          break;
        case '-':
          retVal = a - b;
          break;
          .
          .
          .
        default:
          throw new Exception("Invalid Operator");
          break;
      }
      return retVal;
    }
    And just pass your operator to it as a character.

    Comment

    • BurnTard
      New Member
      • May 2007
      • 52

      #3
      Oh I see, that's really clever! I've never learned about that type of functions, but I understant how it works. Thanks a lot for the fast response.

      Comment

      • Curtis Rutland
        Recognized Expert Specialist
        • Apr 2008
        • 3264

        #4
        No prob. A few notes on the switch statements:
        In most languages, if you don't "break" out after a case, the code will fall through and execute the next line. In C#, unless your case is empty, you will get an exception. So always remember to break; your cases.

        Good
        Code:
        case 1:
          doSomething();
          doSomethingElse();
          break;
        case 2:
          something();
          break;
        Good (in this case, the code under 2 will be executed for either 1 or 2)
        Code:
        case 1:
        case 2:
          something();
          break;
        Bad
        Code:
        case 1:
          doSomething();
          //the missing break; will throw an exception
        case 2:
          something();
          break;
        Also, the "default" case will be used if none of the other cases are matched.

        Comment

        Working...