I have two functions, one can be compiled and the other cannot. What is the difference?
Does function number 1 assume that case 1 always will be hit, or it just a compiler problem?
public void Test(int x) { switch (x) { case 1: uint cId = (uint)3; break; case 2: cId = (uint)5; //NO ERROR HERE. WHY? break; } } public void DeclaringInsideSwitch(int x) { uint tst = 0; switch (x) { case 1: int y = 3; uint variable = tst; break; case 2: variable++; //ERROR HERE. WHY? break; } }
I tried of course searching for "Declaring variables inside switch case in C#", but to me it just seems like some sort of bug in C# now, preserved for backward compatibility.
// After getting a warning that it was already answered, my question can now be reduced to what it is really about.
Why:
int x; x++;
doesn't this work?
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier.
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
Main Difference between If-else and Switch Case The main differences between the two are: The if-else statement is used to choose between two options, but the switch case statement is used to choose between numerous options. If the condition inside the if block is false, the statement inside the else block is executed.
A switch statement causes control to transfer to one labeled-statement in its statement body, depending on the value of expression . The values of expression and each constant-expression must have an integral type. A constant-expression must have an unambiguous constant integral value at compile time.
Basically, the variable declartion is effectively wider than you think; the second example suffers from "definite assignment" since it is declared (wider), but not actually assigned, so ++
makes no sense on an unassigned value.
If you want scopes per case
, you can do it... just add braces:
switch (x) { case 1: { uint cId = (uint)3; break; } case 2: { uint cId = (uint)5; break; } }
Is it a little vexing? Yes. Is it anti-intuitive? Yes. Will it ever be changed? Unlikely, as it would be a significant breaking change that would stop a lot of existing C# from compiling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With