Start a new project called "SwitchStatements".
Add the following code to your "Main" method:
string currentStatusTrafficLight = "red";
switch (currentStatusTrafficLight)
{
case "green":
Console.Write("The traffic light is showing green");
break;
case "orange":
Console.Write("The traffic light is showing orange");
break;
case "red":
Console.Write("The traffic light is showing red!");
break;
}
Console.ReadLine();
A switch statement like any other code is read from top to bottom. Your application starts with "switch (currentStatusTrafficLight)". "Red" is used for this example, so it will compare each case with "Red".
First up is the case "green". The string "red" is not equal to the string "green", so it will not execute the code "Console.Write("The traffic light is showing green");break;)".
Next up is the case "orange". The string "red" is not equal to orange and like last time that means that the code "Console.Write("The traffic light is showing orange");break" will not be executed.
Your last case is "red". The string "red" is equal to "red", so the code "Console.Write("The traffic light is showing red!");break;" will get executed.
"break" will make your application jump out your switch statement, because you don't want it to compare "red" with any more cases. Not that it matters in this example, because there aren't any more cases to compare "red" with. The keyword "break" will also make your application jump out of a loop. This is useful for when you want to search a name in an array and when you found the name you can jump out of the loop, so it doesn't continue the loop when it isn't necessary.
Every case is basically an if statement. Take the following example condition in an if statement: "("red" == "green");". The string "red" is what you put in the switch: "switch ("red")". After that you make a case for the string "green": "case "green":". Your application compares "red" and "green" like in the if statement its condition.
Source Code SwitchStatements Project
>> Methods
I thought switch statements were getting old, and it's better to use if, if else, else statements. That'll be:
ReplyDeleteif ( currentStatusTrafficLight == 'green' ) {
// code goes here
}
else if ( currentStatusTrafficLight == 'orange' ) {
// code goes here
}
else {
// code goes here
}
you can (should) make the last "else" and "else if", so you don't also execute that code in case of data corruption or garbage data.
ReplyDeleteIt's smarter to leave an "else" at the end and make it output "something went wrong, tell the admin the traffic lights are action up".
ReplyDeleteSwitch statements are definitely not getting "old". Switch statements even exist to prevent what you just typed.
ReplyDelete