In C#, the switch statement functions as a decision-making tool that executes different code blocks depending on the value of a specified expression. This statement, also referred to as a conditional statement, offers a more streamlined and readable alternative to the if-else and ladder if statements.
Syntax of Switch Statement
It has the following syntax.
switch(expression)
{
case expression_value1:
Statement
break;
case expression_value2:
Statement
break;
case expression_value3:
Statement
break;
default:
Statement
}
Where,
- Switch(expression): The value of the expression is initialized once.
- expression_value: It compares the expressions. If they match, the code will be executed and break the program; otherwise, it moves to the next statement.
- break;: It is used to exit the program.
- default: It is an optional part of the switch statement. It can be executed anywhere inside the switch statement.
Flowchart of the Switch Statement in C#
The styling for the switch diagram includes a linear gradient background with specific colors and border radius. It also defines padding, margin, and alignment properties for the diagram elements. The diagram title is centered with a custom color, font size, and weight, along with margin adjustments. The flow nodes within the diagram have padding, border radius, and text styling, with distinct backgrounds for start, end, and process nodes. Arrows are styled with a specific color and size. The switch cases are arranged in a flex container with wrapping, spacing, and alignment properties. Each case box has a defined background, border, border radius, padding, minimum width, and text alignment. The default case box has different border and background colors. Labels within the case boxes have custom colors and font weights, while the action text has a specific color and font size.
Let's explore the flowchart and the process of utilizing the switch statement in C#.
In the initial stage, the switch expression needs to be assessed.
Step 2: Subsequently, the assessed scenario verifies the specified condition.
In this scenario, we evaluate the value within each case. When a case matches, the corresponding code block is executed. If there is no match, the default statement is executed.
Finally, the commands are executed by utilizing a switch case statement.
Simple C# Switch Statement Example
Let's consider a basic example to demonstrate the switch statement in C#.
Example
using System;
namespace SwitchExample
{
class Vowel
{
public static void Main(string[] args)
{
char l; // character data type
Console.WriteLine("Enter any Character: ");
l = Convert.ToChar(Console.ReadLine());
switch(Char.ToLower(l))
{
case 'a':
Console.WriteLine("The entered character is a Vowel");
break;
case 'e':
Console.WriteLine("The entered character is a Vowel");
break;
case 'i':
Console.WriteLine("The entered character is a Vowel");
break;
case 'o':
Console.WriteLine("The entered character is a Vowel");
break;
case 'u':
Console.WriteLine("The entered character is a Vowel");
break;
default:
Console.WriteLine("The entered character is not a Vowel.");
break;
}
}
}
}
Output:
Enter any Character:
i
The entered character is a Vowel
Explanation:
In this instance, we are acquiring a character input from the user and transforming it to lowercase using the ToLower function. Subsequently, the switch statement verifies if the user's input corresponds to a vowel (a, e, i, o, or u). Upon discovering a match, it announces that the character is a vowel; if not, the default case communicates that it is not a vowel.
Calculator Program using Switch Statement in C#
Let's consider a basic example to perform simple mathematical calculations using a switch statement in C#.
Example
using System;
namespace Calculator
{
class Number
{
public static void Main(string[] args)
{
char op; // use character data type
double fnum, snum, result; // use double data type
Console.Write("Enter the first number: ");
fnum = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the second number: ");
snum = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the operator (+, -, *, /): ");
op = Convert.ToChar(Console.ReadLine());
switch (op)
{
case '+':
result = fnum + snum; //addition operation is performed
Console.WriteLine("The sum of the first and second number is " + result);
break;
case '-':
result = fnum - snum; // subtraction operation is performed
Console.WriteLine("The difference of the first and second number is " + result);
break;
case '*':
result = fnum * snum; // multiplication operation is performed
Console.WriteLine("The product of the first and second number is " + result);
break;
case '/':
if (snum != 0)
{
result = fnum / snum;// division operation is performed
Console.WriteLine("The division of first and second number is " + result);
}
break;
default:
Console.WriteLine("Invalid operator.");
break;
}
}
}
}
Output:
Enter the first number: 15
Enter the second number: 20
Enter the operator (+, -, *, /): +
The sum of the first and second numbers is 35
Explanation:
In this instance, we showcase a basic mathematical calculation. Following that, we declare two variables of char and double data types. Subsequently, the user is requested to input two numbers and select an operation. Then, the switch case evaluates the numbers and displays the outcome using the Console.WriteLine method.
Rules for Using Switch Statements
There are several rules for using switch statements in C#. Some of them are as follows:
- In C# , we have to use an integral type (such as int and char) inside every switch expression.
- Every switch statement contains multiple cases.
- When a case matches, the code executes until a break statement is reached.
- Every case must end with a break keyword to stop the execution.
- Every case label should be followed by colon ":".
- The outer and inner switch statements can have to use a default case.
- The default case of the switch statement is also optional.
C# Nested Switch Case
In C#, a nested switch statement is a form of control structure in which one switch statement is nested within another switch statement. This technique is applied when there is a need to make complex decisions based on multiple conditions at different levels.
Syntax of Nested Switch Case
It has the following syntax.
Switch(ch1)
{
Case 'A':
Console.WriteLine(" first part of the switch statement.");
Switch(ch2)
{
case 'A':
Console.WriteLine("Second part of the switch statement.");
break;
case 'B': // inner second part of case code.
}
break;
case 'B': // outer second part of case code.
}
C# Nested Switch Case Example
Let's consider a scenario to demonstrate the nested switch statement in C#.
Example
using System;
namespace NestedSwitchCase {
class Program {
static void Main(string[] args) {
int x = 50;
int y = 100;
switch (x) { //outer switch case
case 50:
Console.WriteLine("This is the first part of the switch statement. ");
switch (y) { //inner switch case
case 100:
Console.WriteLine("This is the second part of the switch statement. ");
break;
}
break;
}
Console.WriteLine("The exact value of x is {0} ", x);
Console.WriteLine("The exact value of y is {0}", y);
Console.ReadLine();
}
}
}
Output:
This is the first switch statement.
This is part of the second switch statement.
The exact value of x is 50
The exact value of y is 100
Explanation:
In this illustration, we have defined two integer variables, x and y. Subsequently, the code employs nested switch statements to evaluate the variables x and y. Ultimately, it evaluates a condition and displays the outcome using the Console.WriteLine method.
Features of Switch Statement
The switch statement has several features in C#. Some of them are as follows:
- In C#, the switch statement is easy to implement as compared if-else statement.
- It makes it easy to execute the complicated problem.
- It handles multiple cases.
- In cases where a variable is compared in many constant values, the switch is usually faster and more efficient than if-else due to compiler optimization.
Limitations of Switch Statement
In C#, the switch statement has several limitations. Some of them are as follows:
- We cannot use the float value in a switch statement.
- It cannot handle complex case conditions or expressions.
- We cannot compare the non-integer type value.
Conclusion
In summary, the switch statement provides a solution to a key issue in programming by managing multiple cases effectively. This construct is advantageous for developers when dealing with complex situations.
C# Switch Statements FAQs
1) What is a switch statement in C#?
In C#, the switch statement functions as a decision-making tool enabling the execution of multiple code segments depending on the value of a specified expression.
No, it is not possible to use the float or double data types in a switch statement in C#.
No, using floating-point types is not permissible within a switch statement.
3) What are the benefits and drawbacks of utilizing a switch statement?
In C#, the switch statement comes with various strengths and weaknesses. Here are a few of them-
Advantages:
- It simplifies the execution of complex problems.
- It manages various scenarios efficiently.
Disadvantages:
- We cannot use floating-point values.
- We cannot use the variable conditions.
- It has limited data types
Is it necessary to include the break keyword for every case in C#?
Yes, the break keyword is utilized to terminate the program flow, making its usage essential.
5) Is it possible to manage string values within a switch statement in C#?
Yes, both C# and Java programming languages are capable of handling string data types.