Skip to content

Commit ddddf3e

Browse files
committed
Add a note for the surprising nature of switch scopes
Fixes dotnet#945.
1 parent 12bf7ec commit ddddf3e

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

standard/basic-concepts.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,25 @@ There are several different types of declaration spaces, as described in the fol
9292
- The syntactic translation of a *query_expression* ([§12.20.3](expressions.md#12203-query-expression-translation)) may introduce one or more lambda expressions. As anonymous functions, each of these creates a local variable declaration space as described above.
9393
- Each *block* or *switch_block* creates a separate declaration space for labels. Names are introduced into this declaration space through *labeled_statement*s, and the names are referenced through *goto_statement*s. The ***label declaration space*** of a block includes any nested blocks. Thus, within a nested block it is not possible to declare a label with the same name as a label in an enclosing block.
9494

95+
> *Note*: The fact that variables declared directly within a *switch_section* are added to the local variable declaration space of the *switch_block* instead of the *switch_section* can lead to surprising code. In the example below, the local variable `y` is in scope within the switch section for the default case, despite the declaration appearing in the switch section for case 0.
96+
>
97+
> <!-- Example: {template:"code-in-main", name:"SwitchSurprise", expectedOutput:["11"]} -->
98+
> ```csharp
99+
> int x = 1;
100+
> switch (x)
101+
> {
102+
> case 0:
103+
> int y;
104+
> break;
105+
> default:
106+
> y = 10;
107+
> Console.WriteLine(x + y);
108+
> break;
109+
> }
110+
> ```
111+
>
112+
> *end note*
113+
95114
The textual order in which names are declared is generally of no significance. In particular, textual order is not significant for the declaration and use of namespaces, constants, methods, properties, events, indexers, operators, instance constructors, finalizers, static constructors, and types. Declaration order is significant in the following ways:
96115
97116
- Declaration order for field declarations determines the order in which their initializers (if any) are executed ([§15.5.6.2](classes.md#15562-static-field-initialization), [§15.5.6.3](classes.md#15563-instance-field-initialization)).

0 commit comments

Comments
 (0)