What is a Switch Statement?
A switch statement is an alternative to multiple if-else statements. It's cleaner and more readable when checking a single variable against multiple values.
When to Use Switch?
- Testing one variable against multiple specific values
- Cleaner than long if-else chains
- Better for menu-driven programs
Basic Syntax
switch (variable)
{
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
case value3:
// Code for value3
break;
default:
// Code if no cases match
break;
}
Simple Examples
Example 1: Day of the Week
int iDay = 3;
switch (iDay)
{
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 day");
break;
}
Example 2: Grade Calculator
char cGrade = 'B';
switch (cGrade)
{
case 'A':
Console.WriteLine("Excellent! (90-100)");
break;
case 'B':
Console.WriteLine("Good! (80-89)");
break;
case 'C':
Console.WriteLine("Average (70-79)");
break;
case 'D':
Console.WriteLine("Below Average (60-69)");
break;
case 'F':
Console.WriteLine("Failed (Below 60)");
break;
default:
Console.WriteLine("Invalid grade");
break;
}
The break Statement
The break
statement is crucial - it exits the switch block.
int iNumber = 2;
switch (iNumber)
{
case 1:
Console.WriteLine("One");
break; // Exits switch
case 2:
Console.WriteLine("Two");
break; // Exits switch
case 3:
Console.WriteLine("Three");
break; // Exits switch
}
Without break (causes error):
switch (iNumber)
{
case 1:
Console.WriteLine("One");
// Missing break! Will cause compile error
case 2:
Console.WriteLine("Two");
break;
}
The default Case
The default
case handles all values not covered by other cases.
int iMonth = 13;
switch (iMonth)
{
case 1:
Console.WriteLine("January");
break;
case 2:
Console.WriteLine("February");
break;
// ... other months
case 12:
Console.WriteLine("December");
break;
default:
Console.WriteLine("Invalid month!"); // Executes for 13
break;
}
Multiple Cases with Same Code
You can group multiple cases together:
int iDay = 6;
switch (iDay)
{
case 1:
case 2:
case 3:
case 4:
case 5:
Console.WriteLine("Weekday");
break;
case 6:
case 7:
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Invalid day");
break;
}
Practical Examples from Course
Example 1: Calculator (From Worksheet 2)
using System;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter first number: ");
double dNum1 = double.Parse(Console.ReadLine());
Console.Write("Enter second number: ");
double dNum2 = double.Parse(Console.ReadLine());
Console.Write("\nEnter an operator (+, -, *, /): ");
char cOperator = char.Parse(Console.ReadLine());
double dResult = 0;
switch (cOperator)
{
case '+':
dResult = dNum1 + dNum2;
break;
case '-':
dResult = dNum1 - dNum2;
break;
case '*':
dResult = dNum1 * dNum2;
break;
case '/':
if (dNum2 == 0)
{
Console.WriteLine("\nWarning: Division by zero is not allowed. Returning 0.");
dResult = 0;
}
else
{
dResult = dNum1 / dNum2;
}
break;
default:
Console.WriteLine("\nInvalid operator. Returning 0.");
dResult = 0;
break;
}
Console.WriteLine($"\nResult: {dNum1} {cOperator} {dNum2} = {dResult}");
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Example 2: Day Task Generator (From Worksheet 4)
using System;
namespace DayTaskGenerator
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
// Generate random number between 1 and 7
int iDayNumber = random.Next(1, 8);
string sDayName;
string sTask;
switch (iDayNumber)
{
case 1:
sDayName = "Monday";
sTask = "Start the week with a team meeting!";
break;
case 2:
sDayName = "Tuesday";
sTask = "Tackle that big coding project!";
break;
case 3:
sDayName = "Wednesday";
sTask = "Midweek: Review progress and plan ahead!";
break;
case 4:
sDayName = "Thursday";
sTask = "Test and debug your code!";
break;
case 5:
sDayName = "Friday";
sTask = "Wrap up tasks and prepare for the weekend!";
break;
case 6:
sDayName = "Saturday";
sTask = "Relax or work on a personal project!";
break;
case 7:
sDayName = "Sunday";
sTask = "Plan for the upcoming week!";
break;
default:
sDayName = "Error";
sTask = "Invalid day selected!";
break;
}
Console.WriteLine($"Today is {sDayName}!");
Console.WriteLine($"Your task: {sTask}");
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Example 3: Monster Hunt Game (From Practical Test 4)
using System;
namespace MonsterHunt
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
Console.WriteLine("=== Monster Hunt ===");
Console.WriteLine("Choose your weapon (enter a number):");
Console.WriteLine("1. Sword");
Console.WriteLine("2. Bow");
Console.WriteLine("3. Magic Staff");
Console.Write("Your choice (1-3): ");
int iWeaponId = int.Parse(Console.ReadLine());
string sWeapon = "";
// Determine weapon
switch (iWeaponId)
{
case 1:
sWeapon = "Sword";
break;
case 2:
sWeapon = "Bow";
break;
case 3:
sWeapon = "Magic Staff";
break;
default:
sWeapon = "Fists";
break;
}
// Generate random monster (1-4)
int iMonsterId = random.Next(1, 5);
string sMonster = "";
string sOutcome = "";
switch (iMonsterId)
{
case 1:
sMonster = "Goblin Horde";
if (sWeapon == "Sword")
sOutcome = "You slash through the goblins with ease! Victory!";
else if (sWeapon == "Bow")
sOutcome = "Your arrows take out some goblins, but it's tough. Draw!";
else if (sWeapon == "Magic Staff")
sOutcome = "Your fireballs decimate the horde! Victory!";
else
sOutcome = "Your fists are no match for the horde. Defeat!";
break;
case 2:
sMonster = "Troll Brute";
if (sWeapon == "Sword")
sOutcome = "You dodge and strike the troll's weak spots! Victory!";
else if (sWeapon == "Bow")
sOutcome = "Arrows barely pierce the troll's thick skin. Draw!";
else if (sWeapon == "Magic Staff")
sOutcome = "Your magic overwhelms the brute! Victory!";
else
sOutcome = "The troll crushes you. Defeat!";
break;
case 3:
sMonster = "Phantom Wraith";
if (sWeapon == "Sword")
sOutcome = "Your blade passes through the wraith. Draw!";
else if (sWeapon == "Bow")
sOutcome = "Arrows are useless against spirits. Defeat!";
else if (sWeapon == "Magic Staff")
sOutcome = "Your magic banishes the wraith! Victory!";
else
sOutcome = "The wraith drains your life force. Defeat!";
break;
case 4:
sMonster = "Dire Wolf";
if (sWeapon == "Sword")
sOutcome = "You fend off the wolf with precise strikes! Victory!";
else if (sWeapon == "Bow")
sOutcome = "Your arrows keep the wolf at bay. Draw!";
else if (sWeapon == "Magic Staff")
sOutcome = "Your magic scares the wolf away. Victory!";
else
sOutcome = "Your fists aren't enough against the wolf. Defeat!";
break;
default:
sMonster = "Unknown Beast";
sOutcome = "A strange creature appears, but you flee the battle.";
break;
}
// Generate random loot (5-25 gold)
int iLootValue = random.Next(5, 26);
Console.WriteLine("\n=== Battle Result ===");
Console.WriteLine($"Weapon: {sWeapon}");
Console.WriteLine($"Monster: {sMonster}");
Console.WriteLine($"Outcome: {sOutcome}");
Console.WriteLine($"Loot Gained: {iLootValue} gold");
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Example 4: Hexadecimal to Decimal Converter (From Practical Test 3)
using System;
namespace HexConverter
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a hexadecimal digit (0-9, A-F): ");
char chHex = char.Parse(Console.ReadLine().ToUpper());
int iDecimal = 0;
if ((chHex >= 'A') && (chHex <= 'F'))
{
switch (chHex)
{
case 'A':
iDecimal = 10;
break;
case 'B':
iDecimal = 11;
break;
case 'C':
iDecimal = 12;
break;
case 'D':
iDecimal = 13;
break;
case 'E':
iDecimal = 14;
break;
case 'F':
iDecimal = 15;
break;
}
}
else if ((chHex >= '0') && (chHex <= '9'))
{
iDecimal = chHex - '0'; // Convert char to int
}
else
{
Console.WriteLine("Invalid hexadecimal digit!");
return;
}
Console.WriteLine($"\nHexadecimal {chHex} = Decimal {iDecimal}");
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Switch with Strings
You can also use switch with strings:
string sCommand = "start";
switch (sCommand)
{
case "start":
Console.WriteLine("Starting program...");
break;
case "stop":
Console.WriteLine("Stopping program...");
break;
case "pause":
Console.WriteLine("Pausing program...");
break;
case "resume":
Console.WriteLine("Resuming program...");
break;
default:
Console.WriteLine("Unknown command");
break;
}
Switch vs If-Else
Use Switch When:
✅ Testing one variable against multiple specific values ✅ Values are constants (numbers, chars, strings) ✅ You have many cases (cleaner code)
Use If-Else When:
✅ Testing ranges (e.g., if (x > 10 && x < 20)
)
✅ Complex conditions with multiple variables
✅ Comparing with variables (not constants)
Comparison Example
Using If-Else:
int iDay = 3;
if (iDay == 1)
Console.WriteLine("Monday");
else if (iDay == 2)
Console.WriteLine("Tuesday");
else if (iDay == 3)
Console.WriteLine("Wednesday");
else if (iDay == 4)
Console.WriteLine("Thursday");
else if (iDay == 5)
Console.WriteLine("Friday");
else
Console.WriteLine("Invalid day");
Using Switch (Cleaner):
int iDay = 3;
switch (iDay)
{
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;
default:
Console.WriteLine("Invalid day");
break;
}
Practice Exercises
Exercise 1: Menu System
Create a simple menu: 1. Add 2. Subtract 3. Multiply 4. Divide 5. Exit
Use switch to handle user selection.
Exercise 2: Month Days
Get month number (1-12), display number of days: - January, March, May, July, August, October, December: 31 days - April, June, September, November: 30 days - February: 28 days
Exercise 3: Traffic Light
Input: R (Red), Y (Yellow), G (Green) Output: - Red: "Stop" - Yellow: "Slow down" - Green: "Go" - Other: "Invalid light"
Common Mistakes to Avoid
❌ Forgetting break statement:
switch (iNumber)
{
case 1:
Console.WriteLine("One");
// Missing break! Compile error
case 2:
Console.WriteLine("Two");
break;
}
✅ Correct:
switch (iNumber)
{
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
}
❌ Using variables in case (must be constants):
int iValue = 5;
switch (iNumber)
{
case iValue: // WRONG! Must be constant
Console.WriteLine("Match");
break;
}
✅ Correct:
switch (iNumber)
{
case 5: // Constant value
Console.WriteLine("Match");
break;
}
❌ Trying to use ranges:
switch (iAge)
{
case 0-12: // WRONG! Can't use ranges
Console.WriteLine("Child");
break;
}
✅ Use if-else for ranges:
if (iAge >= 0 && iAge <= 12)
{
Console.WriteLine("Child");
}
Key Takeaways
✅ Switch tests one variable against multiple values
✅ Always include break
after each case
✅ Use default
to handle unmatched values
✅ Can use with int, char, string, enum
✅ Cannot use with ranges or complex conditions
✅ Cleaner than long if-else chains
✅ Multiple cases can share the same code block
Next Topic: C# While and Do-While Loops