Certainly! In C#, the switch
statement is a control flow statement that allows you to execute different blocks of code based on the value of an expression. It's often used as an alternative to long chains of if-else
statements when you have multiple conditions to check. Here's a simple explanation with an example:
Syntax: The switch
statement consists of the switch
keyword followed by the expression to evaluate, curly braces {}
, and a series of case
labels.
case
labels: Each case
label represents a possible value of the expression. When the expression matches a case
label, the corresponding block of code executes.
default
case: Optionally, you can include a default
case, which executes if none of the case
labels match the expression.
Here's an example that demonstrates the usage of the switch
statement:
Example
using System;
class Program
{
static void Main()
{
int dayOfWeek = 3; // Let's assume it's Wednesday
switch (dayOfWeek)
{
case 1:
Console.WriteLine("It's Monday.");
break;
case 2:
Console.WriteLine("It's Tuesday.");
break;
case 3:
Console.WriteLine("It's Wednesday.");
break;
case 4:
Console.WriteLine("It's Thursday.");
break;
case 5:
Console.WriteLine("It's Friday.");
break;
case 6:
Console.WriteLine("It's Saturday.");
break;
case 7:
Console.WriteLine("It's Sunday.");
break;
default:
Console.WriteLine("Invalid day.");
break;
}
}
}
Explanation:
dayOfWeek
set to 3
, assuming it's Wednesday.switch
statement evaluates the value of dayOfWeek
.dayOfWeek
matches any of the case
labels, the corresponding block of code executes.dayOfWeek
is 3
, the block of code under case 3
executes, printing "It's Wednesday.".break
statement is used to exit the switch
statement once a match is found. Without break
, the execution would continue to the next case, which is called "fall-through."case
labels match, the default
case executes. In this example, if dayOfWeek
had a value other than 1
to 7
, it would print "Invalid day.".This is a simple example of how you can use the switch
statement to execute different blocks of code based on the value of an expression.