Question:
C# case statements question?
bobman74
2007-12-18 11:48:40 UTC
switch (Int32 someInt)
{
case 1:
String someStr;
break;
case 2:
String someStr; //Exception ?????
break;
}

Why does a String declared for case 1 exist in case 2? Don't these work like code blocks?
Four answers:
2007-12-18 15:20:58 UTC
If you add extra braces, like the code below, it will work fine. The reason this has to be like this, is because in case/switch statements, the default behavior is to 'fall through' to the next case, unless you have a break or a return. I generally find it the best coding practice to break up the scope, as below, or to declare your variables prior to the switch statement if you want to use a variable through multiple cases.



switch (Int32 someInt)

{

case 1:

{

String someStr;

break;

}

case 2:

{

String someStr; //Exception ?????

break;

}

}
2007-12-18 11:54:37 UTC
In a compiled language like C# two variables in the same scope cannot have the same name because the compiler has to allocate them at compile time - ie it has to allocate space for both variables even if one is not used.
Nur S
2007-12-18 11:58:08 UTC
re-format your case in c++ , i'll work it out for you, just

to be sure
?
2016-11-04 03:22:19 UTC
The change assessments the AnnualMiles which isn't the character R, S or G. char prestige; if(AnnualMiles<30000) prestige = 'R'; if(AnnualMiles<50000) prestige = 'S'; if(AnnualMiles<70000) prestige = 'G'; change(prestige) { case 'R': cout<<"time-honored prestige"; injury; case 'S': cout<<"SILVER ELITE prestige"; injury; case 'G': cout<<"GOLD ELITE prestige"; injury; default: cout<<"PLATINUM ELITE prestige"; }


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...