You've basically asked about C#'s scoping rules. Eric Lippert has answered this question a few times, here he is talking about it on StackOverflow:
http://stackoverflow.com/a/2050864 Typically the C# designers lent on the side of explicitness where the compiler might do something you didn't expect. In this case, if you declare a variable with the same name in two different switch cases, should you be able to refer to it outside the select? Is it two variables, or different initializations of the same one? What if they differ by type? What happen if one of the cases doesn't declare the variable? And (more relevantly) how much effort does the compiler (and language designers) have to put into thinking about the edge cases, vs just not allowing it in the first place (and implementing something more useful instead)? On 4 Jun 2013 10:16, "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 >
