I just “discovered” the switch statement today, and have been trying to figure it out. For some reason, the example I made is not working, and I would like to know why. If anyone can see what’s wrong, please post an answer! The code, as well as the error, are bellow.
error CS0152: The label `case -2:' already occurs in this switch statement
switch(DateTime.Today.Month)
{
case 1:
Debug.Log ("case 1");
season = 3;
world.renderer.material = winterGround;
break;
case 2 - 4:
Debug.Log ("case 2 - 4");
season = 0;
world.renderer.material = springGround;
break;
case 5 - 7:
Debug.Log ("case 5 - 7");
season = 1;
world.renderer.material = summerGround;
break;
case 8 - 10:
Debug.Log ("case 8 - 10");
season = 2;
world.renderer.material = autumnGround;
break;
case 11 - 12:
Debug.Log ("case 11 - 12");
season = 3;
world.renderer.material = winterGround;
break;
default:
Debug.Log ("There is an error!");
break;
}
“case 2 - 4:” is read as “case 2 minus 4”, which translates to -2. same for 5 - 7, etc.
A case can only contain one value. But you can do the following:
switch(DateTime.Today.Month)
{
case 1:
Debug.Log ("case 1");
season = 3;
world.renderer.material = winterGround;
break;
case 2:
case 3:
case 4:
Debug.Log ("case 2 - 4");
season = 0;
world.renderer.material = springGround;
break;
case 5:
case 6:
case 7:
...
break;
...
}
If you then call case 2 it will go through all the code until the next break statement. So case 2, case 3, and case 4 will all execute the same code.
Switches are very handy, but I think you might be misunderstanding one crucial detail: switches will only check for equality against individual constant values, not ranges or variables.
You set a number of cases using literal expressions:
case 2 - 4:
case 5 - 7:
case 8 - 10:
I’ve never seen that done, before, but I believe the compiler is simplifying all of those expressions. And what do they have in common? All of the expressions I quoted will evaluate to the same number:
case -2:
case -2:
case -2:
case -2:
Recognize that number from your error message?
Within a switch, each case value must be unique.
You may have an easier time with other control structures (array indexing, binary searching, a simple series of if-else blocks, or so on), but that seems to be beyond the scope of your original question.