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.