Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# allow statements after a case but not before it?

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; } 
like image 868
rtuner Avatar asked May 22 '13 14:05

rtuner


People also ask

Why does letter C exist?

Like the letter G, C emerged from the Phoenician letter gimel (centuries later, gimel became the third letter of the Hebrew alphabet). In ancient Rome, as the Latin alphabet was being adapted from the Greek and Etruscan alphabets, G and C became disambiguated by adding a bar to the bottom end of the C.

Does the letter C need to exist?

This is a very important rule considering about 25% of words in our language contain a C.] So why do we need a C? When we combine the C with an H we DO make a unique sound. Without a C we would go to Hurch instead of Church, we would listen to a Hime instead of a Chime, etc.

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".

Why does C make two sounds?

In the Latin-based orthographies of many European languages, including English, a distinction between hard and soft ⟨c⟩ occurs in which ⟨c⟩ represents two distinct phonemes. The sound of a hard ⟨c⟩ often precedes the non-front vowels ⟨a⟩, ⟨o⟩ and ⟨u⟩, and is that of the voiceless velar stop, /k/ (as in car).


1 Answers

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

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

That is, x is declared inside a case statement (though after a break), where it is valid. However, directly inside a switch statement it’s invalid – the only valid statements there are case and default.

Furthermore, const declarations are evaluated at compile time, so x is defined even though there’s a break statement before.

However, note that the Mono C# compiler will not compile this code, it complains that “the name ‘x’ does not exist in the current scope” so Mono seems to implement more checks than the .NET compiler. However, I can’t find any rules in the C# standard which forbid this use of the const declaration so I assume that the .NET compiler is right and the Mono compiler is wrong.

like image 108
Konrad Rudolph Avatar answered Sep 23 '22 08:09

Konrad Rudolph