Inside a switch statement, is there any way to refer to the value being switched?

I have a block of code like

switch ( eqtn[curidx] )
{ 
    case Calculator.NOT:
        negateNextOp = true; 
        break;
        // CURMODE remains PARSEMODE.OPER
    case Calculator.OR:
    case Calculator.AND:
    case Calculator.XOR:
        lastop = eqtn[curidx++]; // Set last operator equal to the one at curidx; increment curidx
        CURMODE = PARSEMODE.NUM; // Expecting the next portion of the equation to be a number
        break;
    default: 
         throw new Exception(String.Format("At index {0}, encountered character {1} where expected to encounter beginning of operator",
                                       curidx,
                                       eqtn[curidx])
                             ); // Handle unexpected character 
}

and, as you can see, twice inside the switch statement I refer to eqtn[curidx], the number being switched. This seems like it could be made more elegant and optimal. I know that when a switch statement is compiled, the value inside the paranthesis something that is "cached" when the code runs and hits the switch statement. Since that value is the same as eqtn[curidx], it could result in having two of the same value at different memory addresses (Right?) and that would be useless.

Is there some equivalent of a this to refer to the value current being switched while inside the switch block?

Upvotes: 2

Views: 145

Answers (1)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391576

No, there is no way to refer to "what is being switched on" since the compiler does not in any way create a variable for you that you can access.

Whether the compiler actually caches the value or not depends on things that are outside your control.

If you need a cached copy, which may often be a good idea, you will have to make one yourself using a variable:

var op = eqtn[curidx];
switch (op)
{
    ...

This may be beneficial for several reasons:

  1. It makes the code easier to read, you don't need to parse and grok a larger expression to see that it is in fact the same value that is being switched on.
  2. It makes the code easier to get correct, you don't risk copy/pasting a bug and fixing it in N-1 places later.
  3. The act of evaluating that expression may have a cost, which is now only incurred once.

Upvotes: 2

Related Questions