The switch statement in C# is a control flow statement that executes one out of many possible code blocks based on the value of an expression. It is an alternative to using multiple if-else if statements when you need to compare a single value against multiple possible values.
The switch-case structure chooses which part of the programming code to execute based on the calculated value of a certain expression (most often of integer type).
A good practice when using the switch statement is to put the default statement at the end, to have easier-to-read code.
Syntax:
switch (expression)
{
case value1:
// Executes this block if expression equals value1
break;
case value2:
// Executes this block if expression equals value2
break;
// Additional cases can be added
default:
// Executes if none of the cases match
break;
}
Expression:
- expression: This is the value or variable that you want to test.
- case value: Each case represents a potential match. If the expression matches the value, the corresponding block of code is executed.
- break: After executing a case, the break statement is used to exit the switch block. If you omit the break, the code will “fall through” to the next case (which is not allowed in C#).
- default: This is an optional block that executes if none of the case values match the expression.
Example 1:
using System;
class MyExample
{
static void Main()
{
int day = 2;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
}
}
Output:
Example2:
using System;
enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
class ProgramExample
{
static void Main()
{
Day today = Day.Friday;
switch (today)
{
case Day.Monday:
Console.WriteLine("Start of the work week!");
break;
case Day.Friday:
Console.WriteLine("End of the work week!");
break;
default:
Console.WriteLine("It's a regular day.");
break;
}
}
}
Output:
C# switch Statement – Interview Questions
Q 1: What is switch statement?
Q 2: Which keyword ends a case?
Q 3: Is default case mandatory?
Q 4: Can switch use string values?
Q 5: Is switch faster than if-else?
C# switch Statement – Objective Questions (MCQs)
Q1. Which keyword is used to create a multiple-branch selection based on a variable’s value?
Q2. Which keyword is used to define a branch inside a switch statement?
Q3. What happens if there is no break statement in a case block?
Q4. Which keyword defines a default block if none of the cases match?
Q5. Which data types can be used in a switch expression in C#?