I need to declare a variable inside an if
statement. Then I will use it on the outside. But as far as I know, there are no external variables in C#. But I need to do this.
I have two classes both derived from one class.
Base class: Operand
Derived classes: NormalOperand
SpecialOperand
bool normal
Declared somewhere
if(normal)
NormalOperand o = stack.Pop() as NormalOperand;
else
SpecialOperand o = stack.Pop() as SpecialOperand;
I don't want to deal this differences below. Is there any hack to do that? Or do I have to deal with it everywhere I do something related to this?
I don't see the issue, just declare o
as the base class Operand
.
Operand o = stack.Pop(); // add as Operand if needed
Later if you need to know the type of o
(using virtual/abstract methods on base class should avoid this) then use:
if (o is NormalOperand)
{
// TODO: maybe check for null
(o as NormalOperand).NormalSpecificMethod();
}