What is the difference and why does Switch Case work like this in C#? [duplicate]

  • A+

This question already has an answer here:

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.


int x; x++; 

doesn't this work?


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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: