The below code works fine:
ListControl lstMyControl;
if (SomeVariable == SomeEnum.Value1)
{
lstMyControl = new DropDownList();
}
else
{
lstMyControl = new RadioButtonList();
}
lstMyControl.CssClass = "SomeClass";
Whereas the below code won't compile:
ListControl lstMyControl;
switch (SomeVariable)
{
case SomeEnum.Value1:
lstMyControl = new DropDownList();
break;
case default:
lstMyControl = new RadioButtonList();
break;
}
lstMyControl.CssClass = "SomeClass";
In the second example the compiler says that i am trying to set a property on a variable that has not been instantiated. In either case lstMyControl must be instantiated, but the compilr can't seem to follow that code paths through the switch statement to see that. In the above simple example i would just use if/else. But there are a few times when I have wanted to do something like this with 10 different classes that all inherit from the same base class and having a 10 if/elseif statements is annoying when a switch statement is what i should be using.
ListControl lstMyControl;
switch (SomeVariable)
{
case SomeEnum.Value1:
lstMyControl = new DropDownList();
break;
default: //Don't prefix with "case"
lstMyControl = new RadioButtonList();
break;
}
lstMyControl.CssClass = "SomeClass";
It works as long as you don't prefix "default" with "case" (as Earlz says above). This snippet compiles fine. I'm confused by the error message you're seeing though, removing the "case" gives me a syntax error which is not what you're seeing. Is there something else going on?
ListControl lstMyControl;
int switchVar = 0;
switch (switchVar)
{
case 1:
lstMyControl = new DropDownList();
break;
default:
lstMyControl = new RadioButtonList();
break;
}
lstMyControl.CssClass = "SomeClass";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With