Connecting Tech Pros Worldwide Help | Site Map

Can I save an operator in a variable?

Member
 
Join Date: May 2007
Posts: 50
#1: Feb 4 '09
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
Expand|Select|Wrap|Line Numbers
  1.  
  2. protected void button_add(object sender, EventArgs e)
  3. {
  4. operatorvar opx=+;}
  5. protected void button_equals(object sender, EventArgs e)
  6. {
  7. int answer=a opx b;}
  8.  
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.
insertAlias's Avatar
Forum Leader
 
Join Date: Apr 2008
Location: San Antonio, TX (USA)
Posts: 2,608
#2: Feb 4 '09

re: Can I save an operator in a variable?


What I'd do in that situation is write a method like this:
Expand|Select|Wrap|Line Numbers
  1. //i'm just doing this off the top of my head, haven't tested this code
  2. private double PerformOperation(double a, char op, double b)
  3. {
  4.   double retVal = 0;
  5.   switch(op)
  6.   {
  7.     case '+':
  8.       retVal = a + b;
  9.       break;
  10.     case '-':
  11.       retVal = a - b;
  12.       break;
  13.       .
  14.       .
  15.       .
  16.     default:
  17.       throw new Exception("Invalid Operator");
  18.       break;
  19.   }
  20.   return retVal;
  21. }
And just pass your operator to it as a character.
Member
 
Join Date: May 2007
Posts: 50
#3: Feb 4 '09

re: Can I save an operator in a variable?


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.
insertAlias's Avatar
Forum Leader
 
Join Date: Apr 2008
Location: San Antonio, TX (USA)
Posts: 2,608
#4: Feb 4 '09

re: Can I save an operator in a variable?


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
Expand|Select|Wrap|Line Numbers
  1. case 1:
  2.   doSomething();
  3.   doSomethingElse();
  4.   break;
  5. case 2:
  6.   something();
  7.   break;
Good (in this case, the code under 2 will be executed for either 1 or 2)
Expand|Select|Wrap|Line Numbers
  1. case 1:
  2. case 2:
  3.   something();
  4.   break;
Bad
Expand|Select|Wrap|Line Numbers
  1. case 1:
  2.   doSomething();
  3.   //the missing break; will throw an exception
  4. case 2:
  5.   something();
  6.   break;
Also, the "default" case will be used if none of the other cases are matched.
Reply

Tags
asp.net, c sharp, operator, session, variable