Alright so I get it’s like a big “if, else” statement, and I know the structure of it, but I’m a little confused with the “case”, is the case the current value of the variable? And how do you write a case? Is it: case “value of variable”:, or are there no “”. Also how do you close it, do you just end it with a }? Thanks!
var a;
a = something;
switch (a)
{
case 1: // if a is an integer
Debug.Log("a is an integer");
break;
case "1": // if a is a string
Debug.Log("a is a string");
break;
case default:
Debug.Log ("none of the above");
break;
}
The variable named in the ‘switch’ line is the current value of the variable, of course.
Those listed in each ‘case’ are what to match with. Use the default if you need a catch-all.
While this is an old Question, as there are no accepted answer and the link come up really high on Google, I’ll put my 2 cents in and explain the switch statement in a way that almost anybody can understand.
First, as stated by the question, the Switch is a conditional statement or, in simple terms, a “what if” kind of condition. Its use is similar to that of the “if/else” conditional statement, but depending on the port (target device), its internal use is quite different, hence why some loath its use (a.k.a. deeply hate) because it’s quite easy to fall into a rabbit hole while using it. (A rabbit hole is a way of saying that you work in circle while never finding a way out of a problem. It’s based on Alice in the Wonderland.)
The switch’s structure is like this :
switch (condition)
{
case ConditionA:
// Do something.
break;
case ConditionB:
// Do Something Else
break;
case ConditionC:
// Do something else else. ;)
break;
}
Within the parentheses (*) after switch, it requires the source of the condition. It can be any kind of parameters that are set like an integer internally. This is what, for some, makes it different than an “if” statement. What this means is that it can be an integer, a boolean, an Enum, a state, etc. One thing that is important to remember is that it has some limitation as to how deep it can get its value. this means that it might be required to cache the conditional parameter before using it in a Switch statement. This is one of the main difference with an “if” statement as the Switch doesn’t complete deep interpretation. While C-Sharp in Unity might allow some leeway around those limitation, this is actually because of how it manage the switch statement internally and this might result in minor performance drop in the long run.
For example, you should not use .count or .length or any kind of “deep” getters directly in the switch, but instead get the getters’ value in a pre-made parameter (cached) such as an integer value or whatever. Switch statement takes only pre-cached value.
Something like this:
int Data_Length = 0;
Data_Length = WhateverArray.Length();
switch (Data_Length)
{
default:
// Do something if anything else.
break;
case 2:
// Do Something
break;
case 3:
// Do something else
break;
}
That example isn’t the best, but it does give you one thing that switch statement can’t do. You can’t give imprecise data to a switch() statement like you can in an if() statement.
//This can't be done properly with a switch()
if( Data_Length >= 5){
// Do something
}
else{
// Do something else
}
//To do something like this with a switch, it would have to be like this:
switch (Data_Length){
default :
//Do something else
break;
case 0:
//Do something
break;
case 1:
//Do something
break;
case 2:
//Do something
break;
case 3:
//Do something
break;
case 4:
//Do something
break;
case 5:
//Do something
break;
}
As such, you can’t use conditional statement (>=, <= , > and <) as cases nor uncached values (like case a + b: wouldn’t work)
Another limitation of the switch statement depends on the targeted device. Depending on the target device, Unity might convert the switch to a different statement internally and, in some case, not take the whole switch statement condition which will end up breaking your project. As another example, building a project for Android might break the switch statement as the build will automatically convert the switch to a series of If() statement internally. I made a project to test it out and I created a single function that took an integer in which a single switch statement ran and this managed the whole main menu’s buttons effects of a project of mine. A total of 86 conditions (cases) set in the switch statement. Building the Android APK made the cases after 42 to simply not work at all. The exact same project was working 100% on a build for PC and even with a direct conversion to WebGL.
Still, with all those things about the switch statement, what use can this have?
The switch() is lighter, internally, than if() as while the block (cached data) is of similar size, it’s actually cut down to only the active case(s) in the CPU (if the switch was not converted during the built). To put it in simple terms, both take around the same amount of memory in the RAM, but while the if() will load its whole conditions (even those that are not active) through the CPU thread, the switch() will only run the case that is active. If you got multiple if() and else() statements in row, like 5, the CPU will have to read all 5 if() and else() statement even if only 1 return true. If you got a switch with 5 cases (including 1 default), the CPU will have to only reach the 1 case that returns true. This makes the switch statement a prime tool with things that have complex ranges of impact on CPU-related performances.
To conclude, switch() statement is the best when you know what you’re dealing with and have full control of it. As soon as you enter the realm of “possibilities” or “chances” or “multi-conditional”, switch loose all its good side. I also suggest to use a single switch per function. Having multiple switch() within switch() in a single function will be one of the biggest readability-related pain you’ll ever face when dealing with codes. Having a switch() that call functions with other switch() allows you to focus one each layer of condition more easily. As I previously stated, the CPU-related performances can be quite efficient with a switch statement. For example, if you use a single scene for multiple game modes, you could use a switch in the Update() function with a single integer to determines which mode is active and controls what is sent to the CPU in real-time.
Yes is a switch statement the case is the current value of the variable you are checking against. You are correct in that a switch statement work in a very similar way to a bunch of if statements or even if else statements. The upside is that a switch statement is much more efficient because you are only checking the variable once and not checking each “if”. The syntax depends on the language you are coding in. If you are using C# you end a case by setting a “break” see syntax below: I have defined “state” as the current “MenuState” and use this switch statement to change what I am drawing. Hope this helps. For further information you can also look at this link: http://msdn.microsoft.com/en-us/library/06tc147t(v=vs.71).aspx
switch (state)
{
case MenuState.DoNothing:
// Do nothing
break;
case MenuState.RenderSelf:
GUI.Window (InGameWindowID, MenuRect(menuSize), doInGameOptionsMenu, "");
break;
case MenuState.RenderSubMenu:
//handle sub-menu rendering here
break;
}
IMHO, don’t waste your time learning switch statements. Learning arrays, functions, classes … will solve so many programming problems for you. Switches are just bad ifs – they’re one of many failed features, like repeat-until loops. “Bunch of switch statements” is programmer slang for bug-ridden program.
I sympathize with switch-users. I learned and used them – the old case 'a', 'A': trick (toLower is easier and faster,) leaving off the break to make lines serve double-purpose … . But, kill your darlings.