Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 614
Ben Robinson Avatar asked Feb 02 '10 16:02

Ben Robinson


2 Answers

ListControl lstMyControl;

    switch (SomeVariable)
    {
       case SomeEnum.Value1:
       lstMyControl = new DropDownList();
       break;
       default: //Don't prefix with "case"
       lstMyControl = new RadioButtonList();
       break;
    }

lstMyControl.CssClass = "SomeClass";
like image 73
Earlz Avatar answered Nov 15 '22 17:11

Earlz


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";
like image 43
MarcE Avatar answered Nov 15 '22 16:11

MarcE