Branching Logic with a Switch...Case

A SWITCH statement is used to branch the logic of your application based on the value of a variable. Unlike an IF statement that executes a code block base on a condition check, the SWITCH statement executes code determined by which potential value the variable matches.


For example, if you wanted to write an application that asks the user how they are feeling, you would want to respond differently depending on their responses.

If they are feeling sad or depressed, you’d respond with “Cheer Up.” If they were mad or upset, you could say, “It will be okay.” “That’s great,” would be a good response for anyone feeling good or happy. In theory, you can do the same thing with an IF…ELSE IF…ELSE statement, but if you have several potential matches, this could result in many ELSE IF statements, which makes the code cumbersome and affect readability.

 if (emotion == "happy" || emotion == "good")
 {
      Console.WriteLine("That's great!");
 }
 else if (emotion == "mad" || emotion == "angry")
 {
      Console.WriteLine("It will get better!");
 }
 else if (emotion == "sad" || emotion == "depressed")
 {
      Console.WriteLine("Cheer Up!");
 }
 else
 {
      Console.WriteLine($"I'm not sure what kind of emotion {userResponse} is.");
 }

As you can imagine, this code could get out of hand as more emotions and responses get added. If you are only reacting to the value of a single variable, then you should use a SWITCH statement to clear things up.


The Switch Statement

The syntax of a SWITCH statement in C# follows:


SWITCH(VALUE TO MATCH)

{

CASE Value One

// Code to execute

BREAK STATEMENT

CASE Value Two

// Code to execute

BREAK STATEMENT

CASE Value Three

// Code to execute

BREAK STATEMENT

DEFAULT

// Code to execute if no match is found

BREAK STATEMENT

}


The value to match is enclosed in parentheses (). The block of code that does the checking for a match is enclosed in the curly brackets {}. Every check for a match must be proceeded by the CASE keyword. The use of this keyword is how the application knows that it should be looking for a match. If a match is found, the application will execute the code for that match. There is no need to continue looking for a match when one has been found, so you should leave the SWITCH statement. The BREAK keyword is used to break out of the SWITCH statement and continue with the application.


Let’s take a look at what our emotion check code looks like when we utilize a SWITCH statement.

switch (emotion)
{
     case "happy":
          Console.WriteLine("That's great!");
          break;
     case "mad":
          Console.WriteLine("It will get better!");
          break;
     case "sad":
          Console.WriteLine("Cheer Up!");
          break;
     default:
          Console.WriteLine($"I'm not sure what kind of emotion {userResponse} is.");
          break;
}

In this code example, the value of the emotion variable is what we are using to find a match. This concept is often verbalized as “the value we are switching on.” The cases are the potential matches for this value. A CASE value must always be a literal value. You can not use a variable in a CASE statement. If you need to compare two variable values, you need to revert to using an IF statement.


When a match is found, the application will display the desired message then break out of the SWITCH statement. The DEFAULT statement works like an ELSE statement. The code following the DEFAULT statement will execute if no matches are found.


Just like the ELSE statement, a DEFAULT statement is optional. You don’t have to add it to your SWITCH statement. However, if you none of your CASE statements have a match for the variable value, then no code will be executed in the SWITCH statement.


If you recall, our original code displayed the same message whether the user entered “happy” or “good.” You can insert additional matches into a SWITCH statement by adding another CASE statement before the code to be executed. The following code snippet demonstrates this.

switch (emotion)
{
     case "happy":
     case "good":
     case "glad":
          Console.WriteLine("That's great!");
          break;
     case "mad":
     case "upset":
     case "furious":
          Console.WriteLine("It will get better!");
          break;
     case "sad":
     case "depressed":
     case "gloomy":
          Console.WriteLine("Cheer Up!");
          break;
     default:
          Console.WriteLine($"I'm not sure what kind of emotion {userResponse} is.");
          break;
}

As you can see, it is easy to add more potential matches for the same branch of code.


Switching ON Numbers

The SWITCH statement is not restricted to string values. You can also look for an equivalent numerical value.


Console.WriteLine("What grade are you in (numerical value)?");
int userGrade = int.Parse(Console.ReadLine());
 
switch (userGrade)
{
     case 1:
     case 2:
     case 3:
          Console.WriteLine("You are amazingly good with a computer!");
          break;
     case 4:
     case 5:
     case 6:
          Console.WriteLine("What's your favorite video game?");
          break;
     case 7:
     case 8:
          Console.WriteLine("You are getting close to high school!");
          break;
     case 9:
     case 10:
     case 11:
     case 12:
          Console.WriteLine("Welcome to High School!!!");
          break;
     default:
          Console.WriteLine("Are you sure you are in school?");
          break;
}

MIXING if AND sWITCH

It’s important to remember that a SWITCH statement is looking for a match. It will not do a conditional check. If you want your application to display something based on a condition after a match is made, you can nest an IF statement inside your CASE.


case 9:
case 10:
case 11:
case 12:
Console.WriteLine("Welcome to High School!!!");
 
if (userGrade < 12)
{
Console.WriteLine($"You have {12 - userGrade} years after this one.");
}
else
{
Console.WriteLine("This is your last year!!!");
}
 
break;

32 views0 comments

Recent Posts

See All