Possible Duplicate:
Variable declaration in c# switch statement
I've always wonderd :
when i write :
switch (temp)
{
case "1":
int tmpInt = 1;
break;
}
the case "1":
region has a region of code which is executed ( until break)
now ,
a waterfall from above can't get into a case of 2
e.g. :
switch (temp)
{
case "1":
int tmpInt = 1;
case "2":
break;
}
//error : break return is missing.
So i assume , they have different regions of executions ( case....break).
so why this errors appears ?
//conflict variable tmpInt is defined below.
p.s. this is just a silly question , still interesting.
In C# the scope is determined solely by braces. If there are none, there is no separate scope. With switch
/case
there is obviously none. What you call »region of execution« has nothing to do at all with where you can refer to a variable. For a contrived example:
int x = 1;
goto foo;
// This part gets never executed but you can legally refer to x here.
foo:
You can do the following, though, if you like:
switch (temp)
{
case "1":
{
int tmpint = 1;
break;
}
case "2":
{
int tmpint = 1;
break;
}
}
In fact, for some switch
statements I do that, because it makes life much easier by not polluting other case
s. I miss Pascal sometimes ;-)
Regarding your attempted fallthrough, you have to make that explicit in C# with goto case "2"
.
Try this
int tmpInt = 0;
switch (temp)
{
case "1":
case "2":
tmpInt = 1;
break;
}
so when the case is 1 or 2 it will set tmpint to 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With