Ok. Brackets will create a closed inner scope. But I am ruminating on the
intricacies of switch vs if-else from a language design point of view. If,
instead of adding brackets to the switch, I remove them from the if-else
and use 2 different variables it is now the if-else that doesn't compile:
if (x == 7)
string foo = "a"; // Invalid embedded statement
else
string bar = "b"; // Invalid embedded statement
switch (x)
{
case 7:
string foo = "a"; // No problems
break;
default:
string bar = "b"; // No problems
break;
}
As I said, it's a philosophical question - maybe better suited for a Friday.
On 4 June 2013 13:09, David Richards <[email protected]> wrote:
> 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
>>
>
>