Why can't C# compiler follow all code paths through a switch statement
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 foll开发者_如何转开发ow 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";
精彩评论