Why does C # allow instructions after an event, but not before?

Why does C # allow this:

var s = "Nice"; switch (s) { case "HI": break; const string x = "Nice"; case x: Console.Write("Y"); break; } 

But not this:

 var s = "Nice"; switch (s) { const string x = "Nice"; case x: Console.Write("Y"); break; } 
+63
c # switch-statement
May 22 '13 at 14:16
source share
3 answers

Since your indentation is misleading, the first code is actually:

 var s = "Nice"; switch (s) { case "HI": break; const string x = "Nice"; case x: Console.Write("Y"); break; } 

That is, x declared inside the case (although after break ), where it is valid. However, directly inside the switch its value is invalid - the only valid statements are case and default .

In addition, const declarations are evaluated at compile time, so x is determined even if the sentence is a break .

However, note that the Mono C # compiler does not compile this code, it complains that the "name" x does not exist in the current scope ", so Mono seems to perform more checks than the .NET compiler. However, I cannot find any or rules in the C # standard that prohibit this use of the const declaration, so I assume that the .NET compiler is right and the Mono compiler is wrong.

+119
May 22 '13 at 14:18
source share

Since the language specification does not allow const directly in your switch (only case and default value are allowed):

 switch (expression) { case constant-expression: statement jump-statement [default: statement jump-statement] } 

Where:

expression: Integral or string expression.
statement: built-in statement (s) that must be executed if control is passed in case or default.
jump-statement: A jump-statement: that transfers control from the enclosure.
constant-expression: Control is transferred to a specific case in accordance with the value of this expression.

In the first case, const is part of your case logic. The const command will only work because it is overwritten at compiletime, and not at runtime.

+7
May 22 '13 at 14:20
source share

... because switch does this

 jump_to_the_label_matchig(s) { label1: ... done_quit_this; label2: ... done_quit_this; d'oh: ... done_quit_this; } 

but not

 now_jump_to_the_label_matchig(s) { le'mme_wander_around_doing_things_that_could_have_been_done_before_me; label1: ... done_quit_this; label2: ... 

I am sure that if it were allowed, you would find people ready to do all their programming there :-)

+1
May 30 '13 at 3:34
source share



All Articles