2

So if I have a switch with 3 cases, each case has duplicate local variables declared in them. You would think that the variables would be local to that case so you should be able to use the same name repeatedly. However, this doesn't appear to be the 'case'.

Apparently the other case blocks can see the variables in each other.

Okay, no big deal right? Except that when you try and access that variable that it can obviously see, it says it can't see it???

int index = list.SelectedIndex;

switch(index){

case(0):
   bool val = true;  //First declaration s'allll good
   if(val) //No issues here either obviously
      MessageBox.Show("Huh?");
   break;

case(1):
   bool val = true;  //Says it already exists??
   if(val) 
      MessageBox.Show("Huh?");
   break;
case(2):
   bool val3 = true; //Change the variable name so you can use it however,
   if(val)  //When you try to access the val in case 0 it says it doesn't exist????? 
      MessageBox.Show("Huh?");
   break;
}

Is there an obvious syntax fold in space time I am missing here?

Ondrej Janacek
  • 12,236
  • 14
  • 55
  • 90
Anthony Russell
  • 9,445
  • 10
  • 53
  • 102

3 Answers3

2

The variables, in the IL, are defined to the scope of the switch, so you can't reuse them in the other case statements because it would redefine them.

Likewise, you still have to define the variables for each case (i.e. you've seen how even if one case has the variable the others can't actually leverage its definition).

The better approach, for you, is to define val outside the switch.

Mike Perrenoud
  • 64,877
  • 28
  • 152
  • 226
0

Since cases are just labels, there's no scoping between cases -- they can see variables on the highest scope of the case, hence collisions on your val.

You can either move bool val outside of the switch, or you can enclose the cases in braces to scope it yourself, i.e.

case(0):
{
  bool val = true;
  if (val)
    MessageBox.Show("Huh?");
}
break;
Slate
  • 2,232
  • 30
  • 30
-1

Variables in a switch statement are scoped to the entire switch statement. See this MSDN page at the bottom "The scope of a local variable or constant declared in a switch block is the switch block.".

To get around this, you can either declare the variable above the switch statement or (less cleanly) declare it a single time and re-use throughout the switch statement like so.

int index = list.SelectedIndex;

switch(index){

case(0):
   bool val = true;  //First declaration s'allll good
   if(val) //No issues here either obviously
      MessageBox.Show("Huh?");
   break;

case(1):
   val = true; //Declared in case 0
   if(val) 
      MessageBox.Show("Huh?");
   break;
case(2):
   val = true; //Still declared from case 0
   if(val) 
      MessageBox.Show("Huh?");
   break;
}
bpruitt-goddard
  • 3,034
  • 2
  • 29
  • 34