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
Section 8.5.1 of the C# language spec says:
The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs. It is an error to refer to a local variable in a textual position that precedes the local-variable-declarator of the local variable. Within the scope of a local variable, it is a compile-time error to declare another local variable or constant with the same name.
The block in this case is the switch statement, as blocks are determined by braces.
This happens because you're declaring a local variable with the same name in the same scope, just like intellisense tells you when you hover over the error line.
This is why you really should use curly brackets in each case:
switch(var)
{
case 1:
{
int temp=0;
} break;
case 2:
{
int temp=0;
} break;
}
This fixes the "issue" (which really is not an issue, that's how scopes work).
you are creating the same variable twice i.e. int tmpInt = 1;