C # switch case behavior for declared vars
I am a little confused about the use of terms in terms of the switching case. Why does C # take everything in declared variables case
and automatically declare them at the beginning of the statement switch
?
For example:
switch (test)
{
case "hello":
string demo = "123";
break;
case "world":
demo = "1234";
break;
// not working
case "hello world":
demo = demo + "1234567";
break;
}
I can assign a variable demo
pod case "world"
even though it is declared in case "hello
. But C # seems to only declare the value and not set any value, because getting and setting the value (see below is case "hello world"
not possible).
Why doesn't C # open the term / scope for each case block and close it with a simple breakout or backtrack?
source to share
Because you are not starting a new field. Personally, I almost exclusively use block scopes in my statements case
:
switch (test)
{
case "hello":
{
string demo = "123";
break;
}
case "world":
{
var demo = "1234";
break;
}
case "hello world":
{
var demo = 34;
break;
}
}
In my opinion, the main reasons for this are 1) simplicity and 2) C compatibility There is already a syntax for starting a new block scope and usage { ... }
. You don't need to add another "just because" rule. In C #, it doesn't make much sense that you don't have a separate scope for each of the operators case
, since you are prohibited from reading possibly unassigned variables.
For example, the following is invalid in C #:
switch (test)
{
case 1: string demo = "Hello"; goto case 2;
case 2: demo += " world"; break;
}
Of course, the solution to this is quite simple - just declare a local outer scope switch
and assign a default value to it if necessary.
source to share