Mastering Switch Statements in C#

Olayiwola Osho
8 min readFeb 22, 2024

--

Understanding Switch Statements

What are Switch Statements?

Definition:

A switch statement is a way in programming to check a variable for different values. It helps handle different situations based on what the variable’s value is. It’s useful for making code more straightforward when dealing with various conditions.

Purpose:

They’re handy when you have a variable that can only be certain things, and you want different actions for each possibility.

Think of switch statements as a neater way to handle different cases than using a long list of “if-else” statements. They’re especially useful when your variable can be one of a few specific values.

Anatomy/Syntax of a Switch Statement in C#

switch (expression)
{
case value1:
// Do something if expression equals value1
break;
case value2:
// Do something if expression equals value2
break;
// Additional cases as needed
default:
// Do something if none of the cases match
break;
}
  • switch: It’s like saying, “Let’s decide what to do based on this variable.”
  • expression: This is the variable we’re checking.
  • case value: These are the specific values we’re looking for.
  • default: If none of the cases match, this is our backup plan.

How Switch Statements Work in C#:

Execution Flow:

  • Check the variable once.
  • Go through the cases one by one.
  • If a case matches, do what it says and stop.
  • If none match, do what’s in the default (if there is one).

Matching Cases:

  • It’s like looking for a specific address. When you find it, you stop and do what you’re supposed to do there.

Fall-Through Behavior:

  • By default, once you find a match, you’re done. You don’t keep looking.

Example:

int day = 3;
switch (day)
{
case 1:
Console.WriteLine(“Monday”);
break;
case 2:
Console.WriteLine(“Tuesday”);
break;
case 3:
Console.WriteLine(“Wednesday”);
break;
default:
Console.WriteLine(“Other day”);
break;
}

Explanation:

Variable Initialization:

  • int day = 3;: Declares an integer variable named day and assigns it the value 3.

Switch Statement:

  • switch (day) { … }: Starts a switch statement that evaluates the value of the variable day.

Cases:

  • case 1:: Checks if the value of day is 1.
  • If true, executes the code inside the block: Console.WriteLine(“Monday”);.
  • The break; statement exits the switch statement.
  • case 2:: Checks if the value of day is 2.
  • If true, executes the code inside the block: Console.WriteLine(“Tuesday”);.
  • The break; statement exits the switch statement.
  • case 3:: Checks if the value of day is 3.
  • If true, executes the code inside the block: Console.WriteLine(“Wednesday”);.
  • The break; statement exits the switch statement.

Default Case:

  • default:: If none of the cases above match, this block is executed.
  • In this example, if the value of day is not 1, 2, or 3, it prints: Console.WriteLine(“Other day”);.
  • The break; statement exits the switch statement.

Execution:

Since day is assigned the value 3, the switch statement matches the case 3:.

Therefore, it executes the code inside the Console.WriteLine(“Wednesday”); block.

The output of this code would be: Wednesday.

This code is a simple example of using a switch statement to determine the day of the week based on the value of the day variable.

Code Challenge: Days of the Week

Write a C# program that takes an integer input representing a day of the week (1 for Monday, 2 for Tuesday, …, 7 for Sunday) and prints a message based on the day using a switch statement. If the input is not within the range of 1 to 7, print an error message.

Example Output:

Input: 3
Output: "It's Wednesday!"

Input: 6
Output: "It's Saturday!"

Input: 8
Output: "Error: Invalid day!"

Feel free to use the template below to get started:

using System;

class DaysOfWeekProgram
{
static void Main()
{
Console.Write("Enter a number (1–7) representing a day of the week: ");
int day = int.Parse(Console.ReadLine());
// Your switch statement and output code here
Console.ReadLine(); // To keep the console window open
}
}

Mastering Switch Statement Techniques:

Matching Expressions and Data Types:

Valid Expressions

Switch statements allow you to compare different cases against an expression. This expression can be a variable, a constant, or a literal value.

Example:

int age = 25;

// Using a switch statement to handle different values of age
switch (age)
{
case 18:
// When the age is 18, print a message indicating adulthood
Console.WriteLine("You are now an adult!");
break;

// Additional cases can be added here for other specific ages
default:
// The default case handles all ages that are not explicitly covered
Console.WriteLine("Not a significant age.");
break;
}

Using Different Data Types

When you use a switch statement, you’re checking different options against a value. Each option represents a possible value with a certain data type that you’re evaluating.

Ensure that the data type of the expression matches the types specified in the cases.

char grade = ‘B’;
switch (grade)
{
case ‘A’:
Console.WriteLine(“Excellent”);
break;
case ‘B’:
Console.WriteLine(“Good”);
break;
// Additional cases for other grades
default:
Console.WriteLine(“Needs Improvement”);
break;
}

Null Checks:

Ensure that expressions are not null to prevent unexpected behaviour.

string customerName = GetCustomerName(); // Assume this may return null
switch (customerName)
{
case null:
Console.WriteLine(“No customer name provided.”);
break;
default:
Console.WriteLine($”Hello, {customerName}!”);
break;
}

Defining Case Labels

In a `switch` statement, you can have different cases that represent different possibilities. These cases can be constants (like numbers), variables, or literal values. It’s essential to match both the type and the value of what you’re checking.

Example:

int dayOfWeek = 3;
switch (dayOfWeek)
{
case 1:
Console.WriteLine(“Monday”);
break;
case 2:
Console.WriteLine(“Tuesday”);
break;
// More cases can be added as needed
default:
Console.WriteLine(“Other day”);
break;
}

Matching Values

Each `case` represents a specific condition. When you’re checking values, you need to use the equality (`==`) operator to match exactly what you’re expecting.

Example

int temperature = 25;
switch (temperature)
{
case 20:
Console.WriteLine(“Cool”);
break;
case 25:
Console.WriteLine(“Comfortable”);
break;
// More cases can be added for other temperatures
default:
Console.WriteLine(“Unknown temperature”);
break;
}

Multiple Statements per Case:

You can have multiple statements within a `case` block. This means you can do more than one thing when a particular case matches.

Example:

int month = 6;
switch (month)
{
case 1:
Console.WriteLine(“January”);
break;
case 6:
Console.WriteLine(“June”);
Console.WriteLine(“Summer is here!”);
break;
// More cases can be added for other months
default:
Console.WriteLine(“Other month”);
break;
}

The ‘break’ Keyword

The `break` statement is vital because it exits the `switch` statement after executing the code in a matched `case`. It prevents “falling through” to the next case.

Using the Default Case

The default case handles unmatched expressions, serving as a catch-all for any values that don’t match the specified cases.

char grade = ‘C’;
switch (grade)
{
case ‘A’:
Console.WriteLine(“Excellent”);
break;
case ‘B’:
Console.WriteLine(“Good”);
break;
default:
Console.WriteLine(“Needs Improvement”);
break;
}

Handling Fallback Scenarios

The default case is useful for handling fallback scenarios or providing a default action when none of the specific cases are matched.

int errorCode = HandleOperation();
switch (errorCode)
{
case 0:
Console.WriteLine(“Operation successful!”);
break;
case 1:
Console.WriteLine(“Error: Invalid input”);
break;
default:
Console.WriteLine(“Unknown error occurred”);
break;
}

Nested Switch Statements

Combining Multiple Switches: Nested switch statements involve placing one switch statement inside another, allowing for more complex decision-making logic.

Example

int x = 2, y = 3;
// Outer switch statement based on the value of 'x'
switch (x)
{
// If 'x' is 1, enter this case
case 1:
// Inner switch statement based on the value of 'y'
switch (y)
{
// If 'y' is 1, execute this block
case 1:
Console.WriteLine("x and y are both 1");
break;

// If 'y' is 2, execute this block
case 2:
Console.WriteLine("x is 1, y is 2");
break;
}
// Break out of the outer switch statement after handling //the inner switch
break;
// If 'x' is 2, execute this block
case 2:
Console.WriteLine("x is 2");
break;
}

Explanation:

Outer Switch (switch (x)):

  • Determines the flow based on the value of the variable ‘x’.

Case 1 (case 1):

  • If ‘x’ is equal to 1, the inner switch statement is entered.

Inner Switch (switch (y)):

  • Determines the flow based on the value of the variable ‘y’ when ‘x’ is 1.

Case 1 (case 1):

  • If ‘y’ is equal to 1, the block inside this case is executed.

Case 2 (case 2):

  • If ‘y’ is equal to 2, the block inside this case is executed.

Break (break; after inner switch):

  • The break statement ensures that after handling the inner switch, the control exits the outer switch.

Case 2 (case 2 after the outer switch):

  • If ‘x’ is equal to 2, the block inside this case is executed.

Applying Switch Statements in Real-World Scenarios:

Real World Example

Grade Calculation (Using Integers): (Calculating student grades based on score ranges)
Solution:

using System;

class GradeCalculator
{
static void Main()
{
// Get the student's score
Console.Write("Enter the student's score: ");
int score = int.Parse(Console.ReadLine());
// Calculate the grade based on score ranges
char grade;
if (score >= 90)
{
grade = 'A';
}
else if (score >= 80)
{
grade = 'B';
}
else if (score >= 70)
{
grade = 'C';
}
else if (score >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
// Display the calculated grade
Console.WriteLine($"Student's grade: {grade}");
Console.ReadLine(); // To keep the console window open
}
}

Explanation:

Input:

  • The program prompts the user to enter the student’s score.

Score Ranges and Grade Calculation:

  • The program uses a series of if-else if statements to determine the grade based on score ranges.
  • If the score is 90 or above, the grade is ‘A’.
  • If the score is between 80 and 89 (inclusive), the grade is ‘B’.
  • If the score is between 70 and 79 (inclusive), the grade is ‘C’.
  • If the score is between 60 and 69 (inclusive), the grade is ‘D’.
  • If the score is below 60, the grade is ‘F’.

Output:

  • The program displays the calculated grade for the student.

Example Usage:

Enter the student’s score: 85
Student’s grade: B

This example demonstrates a simple grade calculator that uses integer score ranges to determine the student’s grade.

Code Challenge

Create a C# program that prompts the user to enter the current day of the week (as a string) and prints a corresponding greeting based on the input.

Requirements:

  • The program should ask the user to input the current day of the week using a string.
  • Use a switch statement to determine the input day and print a unique greeting for that day.
  • Include cases for at least three different days, and create a default case for any other day.
  • Display the greeting for the entered day.

Example Output:

Enter the current day of the week: Monday
Greetings for Monday: Hello, start of the week!

Enter the current day of the week: Friday
Greetings for Friday: Happy Friday! Weekend is almost here.

Enter the current day of the week: Sunday
Greetings for Sunday: Enjoy your Sunday relaxation!

Enter the current day of the week: Wednesday
Greetings for Wednesday: Hump day! You're halfway through the week.

Enter the current day of the week: InvalidDay
Greetings for InvalidDay: Not a recognized day. Check your input.

What’s Next?

Congratulations on completing “Mastering Switch Statements in C#”! Now that you’ve mastered the fundamentals of switch statements in C#, it’s time to take your coding journey to the next level.

Next Topic:

Ready to continue your exploration of C# programming? The next topic to dive into is Mastering Arrays in C#. Streamline your code with this powerful data structure, enabling efficient storage and manipulation of collections of items in your programs.

--

--