David,
Try putting braces in:
switch (x)
{
case 7:
{
string foo = "a";
break;
}
default:
{
string foo = "b"; // Compiler not happy because foo
already declared within the switch scope
break;
}
}
David
"If we can hit that bullseye, the rest of the dominoes
will fall like a house of cards... checkmate!"
-Zapp Brannigan, Futurama
On 4 June 2013 12:15, David Burstin <[email protected]> wrote:
> Hi folks,
>
> I was wondering if someone could explain the logic of the following in c#:
>
> Using If-Else:
>
> if (x == 7)
> {
> string foo = "a";
> }
> else
> {
> string foo = "b"; // No problem declaring the string here
> }
>
> Using Switch:
> switch (x)
> {
> case 7:
> string foo = "a";
> break;
> default:
> string foo = "b"; // Compiler not happy because foo
> already declared within the switch scope
> break;
> }
>
> I understand that the scope for the second example is the entire switch
> statement, but why does that need to be the case (pardon the pun)? Is it
> just because of the ability to fall through from one case statement to the
> next (by omitting the break)?
>
> Just as a comparison, the compiler has no problem with the following in VB:
>
> Select Case x
> Case 7
> Dim foo As String = "a"
> Case Else
> Dim foo As String = "b"
> End Select
>