It isn't the flow control constructs doing it, it's the scoping. Possibly the scoping in a for statement is more confusing, but then again, you can alter its behaviour with a compiler switch.
On Tue, Jun 4, 2013 at 1:27 PM, David Burstin <david.burs...@gmail.com>wrote: > 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 <ausdot...@davidsuniverse.com> 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 <david.burs...@gmail.com> 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 >>> >> >> > -- Meski http://courteous.ly/aAOZcv "Going to Starbucks for coffee is like going to prison for sex. Sure, you'll get it, but it's going to be rough" - Adam Hills