views:

228

answers:

2

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.

+14  A: 
ListControl lstMyControl;

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

lstMyControl.CssClass = "SomeClass";
Earlz
@JeffH, yea, just compiled that code and it works for me. I couldn't remember if C# treated `case default` the same as `default`. I would have imagined C# would trigger a compiler error at `case default` really.
Earlz
it does create a compiler error, "Syntax error,'(' expected" it gets a bit confused about the context in which 'default' is being used
Adrian
Wow, yup it does. I wonder what the OP is talking about then?
Earlz
As noted there are other issues with the code posted in the OP
Adrian
A: 

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";
Marc