UPDATE: this question was used as inspiration for this blog; see additional information.
http://ericlippert.com/2009/08/13/four-switch-oddities/
Thanks for the interesting question.
The various answers contain several misunderstandings and incorrect statements, and none of them explains why this is illegal. I will try to be final.
First of all, to be strictly correct, โareaโ is the wrong word to describe a problem. Coincidentally, last week I wrote a blog post about this exact misuse of the โsphereโ; which will be published after my series on iterator blocks, which will work during July.
The correct term to use is the "declaration space". A declaration space is an area of โโcode in which two different things cannot be declared the same. The script described here is a symptom of the fact that the switch section does not define the declaration space, although the switch block does. Since two OP declarations are in the same declaration space and have the same name, they are illegal.
(Yes, the switch block also determines the scope, but this fact is not relevant to the question, since the question is about the legitimacy of the declaration , and not the semantics of identifier search .)
A reasonable question: "Why is it not legal?" The reasonable answer is "okay, why should it be"? You can do this in one of two ways. Or it is legal:
switch(y) { case 1: int x = 123; ... break; case 2: int x = 456; ... break; }
or is it legal:
switch(y) { case 1: int x = 123; ... break; case 2: x = 456; ... break; }
but you cannot have it in both directions. C # designers chose the second way, which seems to be a more natural way to do this.
This decision was made on July 7, 1999, just shyly ten years ago. The comments in the notes from this day are extremely brief, simply stating: โThe case with the switch does not create its own ad space,โ and then gives some example code that shows what works and what doesn't.
To learn more about what was in the minds of designers on that particular day, I would have to offend people a lot about what they thought ten years ago and let them know what is ultimately a trivial problem; I'm not going to do that.
In short, there is no particularly good reason to choose one of the ways; both have virtues. The language design team chose one of the ways because they needed to choose one; the one they chose seems reasonable to me.