Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax
3.
Flowchart
4.
Example: Using the Switch Statement in C#
4.1.
C#
5.
Why do we use Switch Statements instead of if-else statements?
5.1.
Readability
5.2.
Performance
5.3.
Fall-through behavior
5.4.
Expressiveness
5.5.
Maintainability
6.
Using goto in the Switch Statement
6.1.
C#
7.
Example
7.1.
C#
8.
Frequently Asked Questions
8.1.
Can I use variables in switch case labels in C#?
8.2.
Is it possible to nest switch statements in C#?
8.3.
Why should I use a break statement in each case of a switch?
9.
Conclusion 
Last Updated: Jul 25, 2024
Easy

Switch Statement in C#

Author Rahul Singh
0 upvote

Introduction

In C#, the switch statement is a control flow statement that allows you to test a variable against multiple possible values & execute different code blocks based on the matching value. It provides a clean & efficient way to handle multiple conditions, which makes your code more readable & maintainable compared to using a series of if-else statements. 

Switch Statement in C#

 

In this article, we will learn about the syntax of the switch statement, understand its flow using a flowchart, & see practical examples of how to use it in C# programs. We will also discuss why switch statements are often preferred over if-else statements in certain scenarios.

Syntax

The syntax of the switch statement in C# follows a specific structure. Here's the general syntax:

switch (expression)
{
    case value1:
        // Code to execute if expression matches value1
        break;
    case value2:
        // Code to execute if expression matches value2
        break;
    ...
    default:
        // Code to execute if no case matches the expression
        break;
}


Let's understand the structure of above used switch statement syntax:

  1. expression: This is the variable or expression that you want to evaluate. It can be of any data type, such as int, char, string, or an enumeration.
     
  2. case: Each case represents a possible value that the expression can match. You specify the value followed by a colon (:) and the code block to execute if the expression matches that value.
     
  3. break: After each case block, you need to include a break statement. It ensures that once a matching case is found & its code block is executed, the program exits the switch statement & doesn't fall through to the next case.
     
  4. default: The default case is optional, but it's a good practice to include it. It specifies the code block to execute if none of the cases match the expression. The default case doesn't need a break statement since it's the last block in the switch statement.

Flowchart

To visualize the flow of a switch statement, let's look at a flowchart:

Flowchart

The flowchart displays the step-by-step process of a switch statement:

  1. The switch statement begins by evaluating the expression.
     
  2. The expression is compared with the first case value.
  • If there is a match, the code block associated with that case is executed, followed by a break statement to exit the switch.
     
  • If there is no match, the program moves on to compare the expression with the next case value.
  1. The process continues until a matching case is found or all cases have been checked.
     
  2. If no matching case is found, the program executes the code block in the default case (if present).

Example: Using the Switch Statement in C#

  • C#

C#

using System;

class Program
{
static void Main()
{
Console.Write("Enter a number (1-7) to get the corresponding day of the week: ");
int dayNumber = Convert.ToInt32(Console.ReadLine());

switch (dayNumber)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
default:
Console.WriteLine("Invalid input! Please enter a number between 1 and 7.");
break;
}
}
}

Output

Enter a number (1-7) to get the corresponding day of the week: 6
Saturday


This example accepts user input and matches it to a case in the switch. If the input is between 1 and 7, it prints the corresponding day of the week; otherwise, it alerts the user about the invalid input.

Why do we use Switch Statements instead of if-else statements?

While both switch statements & if-else statements can be used to handle multiple conditions, there are several reasons why switch statements are often preferred in certain scenarios:

Readability

  • Switch statements provide a cleaner & more readable structure when dealing with multiple conditions.
     
  • Each case is clearly defined, making it easier to understand the different possible outcomes.
     
  • If-else statements can become nested & complex, especially when dealing with many conditions, making the code harder to read & maintain.

Performance

  • In some cases, switch statements can offer better performance compared to if-else statements.
     
  • The compiler can optimize switch statements more efficiently, particularly when there are many cases.
     
  • If-else statements require sequential evaluation of each condition, which can be less efficient.

Fall-through behavior

  • Switch statements allow for fall-through behavior, meaning that if a break statement is omitted, the program will continue executing the code in the next case.
     
  • This can be useful in certain situations where multiple cases share the same code block.
     
  • If-else statements do not have this fall-through behavior & require explicit handling of each condition.

Expressiveness

  • Switch statements are more expressive when dealing with discrete values or constants.
     
  • They provide a clear way to map specific values to corresponding actions.
     
  • If-else statements are more suitable for complex conditions or ranges of values.

Maintainability

  • Switch statements make it easier to add or remove cases without affecting the overall structure of the code.
     
  • Adding a new case is as simple as adding another case block.
     
  • With if-else statements, adding a new condition may require modifying the existing structure & potentially introducing errors.


Note : It's important to note that switch statements are not always the best choice. If-else statements are still useful in conditions where the conditions are more complex or involve ranges of values. The choice between switch statements & if-else statements depends on the specific requirements of your program & the nature of the conditions you are handling.

Using goto in the Switch Statement

The goto statement in C# can be used within a switch case to jump to another case, which can be useful in certain scenarios where multiple conditions result in the same outcome. 

Let’s see how we can use goto in a switch statement:

  • C#

C#

using System;

class Program
{
static void Main()
{
Console.Write("Enter a number (1-5): ");
int number = Convert.ToInt32(Console.ReadLine());

switch (number)
{
case 1:
Console.WriteLine("You entered one.");
break;
case 2:
case 3:
Console.WriteLine("You entered either two or three.");
goto case 5;
case 4:
Console.WriteLine("You entered four.");
break;
case 5:
Console.WriteLine("Common case for values that are not one or four.");
break;
default:
Console.WriteLine("Invalid input! Enter a number between 1 and 5.");
break;
}
}
}

Output

Enter a number (1-5): 3
You entered either two or three.
Common case for values that are not one or four.


In this example, the input values of 2 or 3 not only print their initial message but also jump to the logic defined under case 5, allowing for the reuse of code blocks and avoiding redundancy. 

Note : It's important to note that we need to use goto very cautiosly, as it can make the code harder to read & maintain if used excessively or inappropriately. In most cases, structured control flow statements like loops & conditional statements are preferred for better code readability & maintainability.

Example

Now, let’s look at the example of using goto in Switch statement. This approach can help manage cases where multiple input scenarios lead to a shared outcome, simplifying the code by avoiding repetition.

  • C#

C#

using System;

class Program
{
static void Main()
{
Console.Write("Enter a month number (1-12): ");
int month = Convert.ToInt32(Console.ReadLine());

switch (month)
{
case 12:
case 1:
case 2:
Console.WriteLine("Winter");
break;
case 3:
case 4:
case 5:
Console.WriteLine("Spring");
break;
case 6:
case 7:
case 8:
Console.WriteLine("Summer");
goto common;
case 9:
case 10:
case 11:
Console.WriteLine("Autumn");
goto common;
default:
Console.WriteLine("Invalid month. Please enter a number between 1 and 12.");
break;
common:
Console.WriteLine("Prepare for the next season!");
break;
}
}
}

Output

Enter a month number (1-12): 4
Spring

 

In this code, the months corresponding to summer and autumn conclude by executing a common action: printing a reminder to prepare for the next season. The goto statement directs the flow from summer and autumn cases to the common label, which follows the switch block.

Frequently Asked Questions

Can I use variables in switch case labels in C#?

No, switch case labels in C# require constant values. Variables cannot be used as they do not meet the requirement of compile-time constancy.

Is it possible to nest switch statements in C#?

Yes, you can nest switch statements within each other. This is useful for checking multiple conditions and handling more complex decision-making processes.

Why should I use a break statement in each case of a switch?

The break statement prevents the execution from falling through to the next case. Without it, multiple case blocks might execute unintentionally, leading to unexpected results.

Conclusion 

In this article, we talked about the switch statement in C#, which provides a convenient way to handle multiple conditions & execute different code blocks based on the matching value. We learned about the syntax of the switch statement, understood its flow using a flowchart, & saw practical examples of how to use it in C# programs. We also discussed why switch statements are usually used over if-else statements in many situations. Apart from this, we discussed the usage of the goto statement within switch statements for more complex control flows. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass