The switch statement lets you choose which code block to execute from among many options.
A switch statement evaluates an expression and executes the code corresponding to the expression’s matching value.
It is similar to if-else statements but with a few key differences. This article will explore the C# switch statement and its various use cases.
Table of Contents
- 1 Syntax
- 2 The break keyword
- 3 The default keyword
- 4 Flowchart switch statement
- 5 Example 1: C# switch Statement
- 6 Example 2: C# switch Statement with grouped cases
- 7 Example 3: Creating a Basic Calculator Program in C# with Switch Statement
- 8 Example 4: Using Enum in a switch statement
- 9 Example 5: Using multiple case statements in one switch
- 10 Why do we use Switch Statements instead of if-else statements?
- 11 Using goto in the Switch Statement
- 12 Case Patterns
- 13 Using when in Switch Expression
- 14 Points to Remember about Switch Case in C#
- 15 FAQs
- 16 Summary
Syntax
The basic syntax of the C# switch statement is as follows:
switch (expression)
{
case value1:
// code to execute when expression == value1
break;
case value2:
// code to execute when expression == value2
break;
default:
// code to execute when none of the above cases match
break;
}
Here, the expression
is the value to be evaluated, and each case is a possible matching value. The default case is executed when no case value matches the expression. The break statement is used to exit the switch block.
Despite its advantage of making the code appear more straightforward than an if-else if statement, the switch statement in C# has certain limitations regarding the data types it can work with. Specifically, the switch statement is only able to handle the following types of data:
- Primitive data types, such as bool, char, and integral types
- Enumerated types (Enum)
- The String class
- Nullable types of data, as mentioned above types.
The break keyword
The break keyword is used in switch statements to exit the switch block and prevent the execution of subsequent case statements.
When a case statement is executed, the program will continue to execute all subsequent case statements until it reaches a break statement. The break statement causes the program to exit the switch block and continue executing the code after the switch block.
If a break statement is not included in a case statement, the program will “fall through” to the next case statement and execute its code. This behavior can be helpful in certain situations, such as when multiple cases should execute the same code.
The default keyword
The default
keyword in a switch statement specifies the code to be executed when none of the cases match the input value. It is optional but recommended to include it to handle unexpected values.
Flowchart switch statement
The following is the flowchart of the C# Switch statement.
Example 1: C# switch Statement
Let’s take a look at an example:
using System;
class Program
{
static void Main()
{
int day = 5;
string dayName;
switch (day)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
Console.WriteLine("Today is " + dayName);
}
}
Output:
//Output: Today is Friday
In this example, the value of the day
variable is 5, so the case 5 block will be executed, and the output will be “Today is Friday”.
Example 2: C# switch Statement with grouped cases
In some cases, we might want to execute the same code for multiple cases. In this scenario, we can group the cases as follows:
using System;
class Program
{
static void Main()
{
char grade = 'B';
switch (grade)
{
case 'A':
case 'B':
case 'C':
Console.WriteLine("Pass");
break;
case 'D':
case 'F':
Console.WriteLine("Fail");
break;
default:
Console.WriteLine("Invalid grade");
break;
}
}
}
In the above example, we use grouped cases to execute the same code for multiple cases. If the grade variable is A, B, or C, the program will output Pass
. If the grade variable is D or F, the program will output Fail
. The program will output an Invalid grade if the grade variable is any other character.
Example 3: Creating a Basic Calculator Program in C# with Switch Statement
Now, let’s take a look at a more complex example. We can use the switch statement to build a simple calculator program:
using System;
class Program
{
static void Main()
{
int num1, num2, result;
char op;
Console.Write("Enter first number: ");
num1 = int.Parse(Console.ReadLine());
Console.Write("Enter second number: ");
num2 = int.Parse(Console.ReadLine());
Console.Write("Enter operator (+, -, *, /): ");
op = char.Parse(Console.ReadLine());
switch (op)
{
case '+':
result = num1 + num2;
Console.WriteLine("Result: " + result);
break;
case '-':
result = num1 - num2;
Console.WriteLine("Result: " + result);
break;
case '*':
result = num1 * num2;
Console.WriteLine("Result: " + result);
break;
case '/':
if (num2 == 0)
{
Console.WriteLine("Cannot divide by zero");
}
else
{
result = num1 / num2;
Console.WriteLine("Result: " + result);
}
break;
default:
Console.WriteLine("Invalid operator");
break;
}
Console.ReadLine();
}
}
Output:
In the above example, we take two numbers, ask for an operator as input from the user, and use the switch statement to perform the corresponding arithmetic operation.
Example 4: Using Enum in a switch statement
Enums are a powerful way to define a set of related values. We can use enums in a switch statement as follows:
using System;
class Program
{
// Using Enum with Switch statement.
enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
static void Main()
{
Days day = Days.Sunday;
switch (day)
{
case Days.Monday:
Console.WriteLine("Today is Monday");
break;
case Days.Tuesday:
Console.WriteLine("Today is Tuesday");
break;
case Days.Wednesday:
Console.WriteLine("Today is Wednesday");
break;
case Days.Thursday:
Console.WriteLine("Today is Thursday");
break;
case Days.Friday:
Console.WriteLine("Today is Friday");
break;
case Days.Saturday:
Console.WriteLine("Today is Saturday");
break;
case Days.Sunday:
Console.WriteLine("Today is Sunday");
break;
}
Console.ReadLine();
}
}
Output:
Today is Sunday
In this example, we are defining an enum
called Days with seven possible values and using the switch statement to output the name of the selected day.
Example 5: Using multiple case statements in one switch
We can use multiple case statements in a single switch block as follows:
using System;
class Program
{
static void Main()
{
int age = 25;
switch (age)
{
case 18:
case 19:
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
Console.WriteLine("You are between 18 and 25 years old");
break;
default:
Console.WriteLine("You are not between 18 and 25 years old");
break;
}
Console.ReadLine();
}
}
In this example, we use multiple case
statements to match a range of values. It can be helpful when we want to execute the same code for a set of related values.
Why do we use Switch Statements instead of if-else statements?
Switch statements are often more concise and easier to read than a series of if-else statements. They also allow for faster execution in some cases, as the compiler can optimize the code for switch statements.
Using goto in the Switch Statement
In C#, we can use the goto
statement to jump to a specific label in a switch block. Here is an example:
using System;
class Program
{
static void Main()
{
int num = 1;
switch (num)
{
case 1:
Console.WriteLine("Case 1");
goto case 2;
case 2:
Console.WriteLine("Case 2");
break;
}
Console.ReadLine();
}
}
In this example, we are using the `goto` statement to jump from `case 1` to `case 2`.
Case Patterns
Starting with C# 7.0, we can use patterns in switch cases to match more complex values. Here are a few examples:
Type Pattern
using System;
class Program
{
static void Main()
{
object obj = "Hello";
switch (obj)
{
case string s:
Console.WriteLine("The object is a string with value " + s);
break;
case int i:
Console.WriteLine("The object is an integer with value " + i);
break;
default:
Console.WriteLine("The object is neither a string nor an integer");
break;
}
}
}
In this example, we are using the type pattern to match the type of the obj
object.
Using when
in Switch Expression
Starting with C# 7.0, you can use the “when” keyword to add additional conditions to a switch expression. These conditions can filter the values of the switch expression and only execute the code in the corresponding case if the condition is true.
Here is an example that uses the “when” keyword in a switch expression:
using System;
public class WhereInSwitchStatement
{
public static void Main(string[] args)
{
int age = 25;
string result = age switch
{
int n when n < 18 => "You are not an adult",
int n when n >= 18 && n < 65 => "You are an adult",
int n when n >= 65 => "You are a senior citizen",
_ => "Invalid age input"
};
Console.WriteLine(result);
}
}
Output:
You are not an adult
Points to Remember about Switch Case in C#
Here are some important points to remember when using switch statements in C#:
- The switch statement’s expression must be evaluated to an integral type or a string.
- Each case statement must end with a break statement unless it is the last statement in the switch block.
- If no case matches the input value, the default case will be executed (if it is defined).
- It is possible to have multiple case statements that execute the same code.
- We can use switch statements with
enums
and custom types by defining a custom equality operator. - Starting with C# 7.0, switch statements can use patterns to match more complex values.
Reference: MSDN-Selection Statements
FAQs
Here are some frequently asked questions (FAQs) about the C# switch statement:
Q: What is a switch statement in C#?
A switch statement in C# is a control statement that allows you to select one of many code blocks to be executed based on the value of an input expression.
Q: What data types can be used with a switch statement in C#?
Primitive data types like bool, char, and integral types, as well as enumerated types and the String class, can be used with a switch statement in C#.
Q: How do you handle unexpected values in a switch statement?
The default case is a catch-all case that is executed when none of the cases match the input value. Including a default case in the switch statement is important to handle unexpected values.
Q: What is a switch expression in C#?
A switch expression is a newer feature in C# that allows you to use a switch statement as an expression, which can be assigned to a variable or used as part of a larger expression.
Q: How do you use the “when” keyword in a switch expression?
The “when” keyword is used to add additional conditions to a switch expression, allowing you to filter the input values and execute code in the corresponding case only if the condition is true.
Summary
In this article, we learned about the switch statement in C#. We have seen several examples of switch statements with different input types, including strings, integers, and enums.
We have also discussed why switch statements are often preferred over if-else statements and some important points to remember when using switch statements in C#. Using switch statements effectively can write more concise, readable, and maintainable code in C#.
You might also like:
- Difference Between if-else and switch: A Side-by-Side Comparison of If-Else and Switch Case
- Singleton Design Pattern in C#: A Beginner’s Guide with Examples
- SOLID Design Principles in C#: A Complete Example
- C# Struct vs Class |Top 15+ Differences Between C# Struct and Class
- 10 Difference between interface and abstract class In C#
- Local vs Global Variables
- Generic Delegates in C# With Examples: Func, Action, and Predicate delegates
- Constructors in C#: A Comprehensive Guide with Code Examples
- Top 5 Difference between Call by Value and Call by Reference
- C# stack vs heap
- Readonly vs const in C#
- C# String VS StringBuilder
- Fields vs Properties In C#: Understanding the difference between Field and Property in C#
Let others know about this post by sharing it and leaving your thoughts in the comments section.
- SQL Server Indexing: Clustered vs Non Clustered Index Explained - March 26, 2023
- Mastering Database Normalization: Best Practices and Techniques - March 25, 2023
- CRM Databases: The Key to Enhanced Customer Engagement and Sales - March 23, 2023