Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Switch/case share the same scope? [duplicate]

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 ?

enter image description here

//conflict variable tmpInt is defined below.

p.s. this is just a silly question , still interesting.

like image 477
Royi Namir Avatar asked Jul 10 '12 08:07

Royi Namir


2 Answers

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 cases. I miss Pascal sometimes ;-)

Regarding your attempted fallthrough, you have to make that explicit in C# with goto case "2".

like image 97
Joey Avatar answered Oct 04 '22 02:10

Joey


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

like image 23
JohnnBlade Avatar answered Oct 04 '22 02:10

JohnnBlade