Switch - Case
6 Feb 2008 @ 07:41AM

Updated: 25 Jan 2010 @ 07:43AM
The final logical operation we'll be looking at is the Switch - Case. Switch case takes a single variable (like name, for instance) and then compares it to one or more possibilities. It's like a specialized if - then -else if - else statement in which only one variable is compared repeatedly. Let's get an example.


A Simple Switch - Case Example

In this example we're examining the variable 'name'. In the case that it's equal to "Satis", we're appending "Hello Master.<br>" to the contentString string. We're then issuing a break; which lets C# know that we're done executing commands. Similarly, if name == "Shiny" we're appending "Hello Mistress.<br>". In the next part, we're looking for Pig and Ox. Notice how there's no break between the case "Pig" and case "Ox". This means that if either "Pig" or "Ox" are matched, the contentString gets "Hello Grabber.<br>" appended to it. Then there's another break and we get a default. Default is exactly the same as an else statement.
Comments (0)
Switch - case is a very useful construct. It's very easy to read and you can put more than one command in each case. For instance, I could stick a ternary operation inside of the switch - case. Let's spruce this switch - case up a bit.


A More Complicated Switch - Case

So, under Satis, we just added a ternary operation. If Satis's occupation == "Web Monkey", we append "Hello Master.<br>" to the contentString string. Otherwise, we append "You suck.<br>". Meanwhile under the Pig and Ox section, after appending the Hello Grabber greeting, I then check to see if the name is "Pig" and if the occupation is "Grabber". If it is, I don't append anything. If it's not, I append "Wait, you're not grabbing any more?".

Hopefully that's pretty clear. If - then - else, ternary operations and switch - case are used constantly throughout all languages I code in. Learning how they work will be of benefit even if you decide not to learn C#. Keep in mind that all of these statements follow specific, logical order. For instance, with the if - then - else statement, the code checks all your conditions until it matches one, then it stops checking. With ternary it's the same thing, though a simple ternary operaion only has two options. If you nest options, you have to evaluate them in order. Finally with a switch - case, a specific case option can only ever appear once within one case. If you try to have it appear more than once you will get an error.

With our logic covered, we'll now look over the different kinds of operators you can use.
Comments (0)