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 together (fall-through) so they share the same outcome. Stack the case labels one after another with no code between them, and only one break at the end:
string grade = "B";
switch (grade)
{
case "A":
case "a":
Console.WriteLine("Excellent - 4 points");
break;
case "B":
case "b":
Console.WriteLine("Good - 3 points");
break;
case "C":
case "c":
Console.WriteLine("Satisfactory - 2 points");
break;
default:
Console.WriteLine("Needs improvement");
break;
}Here, both "B" and "b" fall through to the same block and print "Good - 3 points". This pattern is useful whenever you want uppercase and lowercase inputs, or any set of values, to produce the same result.
Switch can also group cases with different labels that share an outcome:
char dayCode = 'M';
switch (dayCode)
{
case 'M':
Console.WriteLine("Monday");
break;
case 'T':
Console.WriteLine("Tuesday or Thursday");
break;
case 'W':
Console.WriteLine("Wednesday");
break;
case 'F':
Console.WriteLine("Friday");
break;
default:
Console.WriteLine("Unknown day");
break;
}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
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 SafetyPractice on your own: Online C# compiler