Reputation: 135
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 switch
ed. 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 switch
ed while inside the switch
block?
Upvotes: 2
Views: 145
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:
Upvotes: 2