If vs. Switch Comparison
Part of the Logic & Flow section of Coddy's C# journey — lesson 10 of 66.
C# provides two primary ways to handle multiple conditions: if-else statements and switch statements. Each has its strengths in different scenarios.
If-else statements are flexible and can handle any type of condition:
string grade = "B";
if (grade == "A")
{
Console.WriteLine("Excellent");
}
else if (grade == "B")
{
Console.WriteLine("Good");
}
else if (grade == "C")
{
Console.WriteLine("Satisfactory");
}
else
{
Console.WriteLine("Needs improvement");
}Switch statements are cleaner when comparing a single variable against multiple constant values:
string grade = "B";
switch (grade)
{
case "A":
Console.WriteLine("Excellent");
break;
case "B":
Console.WriteLine("Good");
break;
case "C":
Console.WriteLine("Satisfactory");
break;
default:
Console.WriteLine("Needs improvement");
break;
}Switch can group multiple cases that share the same outcome by stacking case labels together — this is called fall-through. When several cases have no code between them, they all execute the same block:
char dayCode = 'S';
switch (dayCode)
{
case 'M':
case 'T':
case 'W':
case 'R':
case 'F':
Console.WriteLine("Weekday");
break;
case 'S':
case 'U':
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Unknown day");
break;
}Here, 'S' and 'U' both fall through to the same Console.WriteLine("Weekend") call. Stacking empty case labels like this is the standard way to group cases in C#.
Challenge
MediumCreate a method called convertGradeToPoints that:
- Takes a letter grade as a string parameter
- Converts it to a numeric grade point using both switch and if-else approaches
- The method should implement both approaches and return the result of the switch implementation
- Use these grade conversions:
- "A" or "a" = 4
- "B" or "b" = 3
- "C" or "c" = 2
- "D" or "d" = 1
- "F" or "f" = 0
- Any other input = -1
Cheat sheet
C# provides two primary ways to handle multiple conditions: if-else statements and switch statements.
If-else statements are flexible and can handle any type of condition:
string grade = "B";
if (grade == "A")
{
Console.WriteLine("Excellent");
}
else if (grade == "B")
{
Console.WriteLine("Good");
}
else if (grade == "C")
{
Console.WriteLine("Satisfactory");
}
else
{
Console.WriteLine("Needs improvement");
}Switch statements are cleaner when comparing a single variable against multiple constant values:
string grade = "B";
switch (grade)
{
case "A":
Console.WriteLine("Excellent");
break;
case "B":
Console.WriteLine("Good");
break;
case "C":
Console.WriteLine("Satisfactory");
break;
default:
Console.WriteLine("Needs improvement");
break;
}Switch statements can group multiple cases (fall-through) to share the same outcome by stacking case labels:
char dayCode = 'S';
switch (dayCode)
{
case 'M':
case 'T':
case 'W':
case 'F':
Console.WriteLine("Weekday");
break;
case 'S':
case 'U':
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Unknown day");
break;
}Try it yourself
public class ConvertGradeToPoints
{
// Implement the convertGradeToPoints method
public static int convertGradeToPoints(string letterGrade)
{
// Write your code here
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety