Skip to content

Experiment with C#'s Case Statements #10

@XTopher13

Description

@XTopher13

Context

From Google's AI's response
In C#, while traditional switch statements only allow discrete constant values for case labels, you can effectively handle ranges of options using several techniques, especially with newer C# features:

  1. switch statement with when clauses (C# 7.0 and later):
    This allows you to add a conditional expression to a case label, effectively creating a range check.
    int score = 75;
    string grade = score switch
    {
    int s when s >= 90 => "A",
    int s when s >= 80 => "B",
    int s when s >= 70 => "C",
    int s when s >= 60 => "D",
    _ => "F"
    };
    Console.WriteLine($"Score: {score}, Grade: {grade}");
  2. if-else if statements:
    This is a classic and straightforward approach for handling sequential ranges.
    int temperature = 25;
    if (temperature >= 30)
    {
    Console.WriteLine("Hot!");
    }
    else if (temperature >= 20)
    {
    Console.WriteLine("Warm.");
    }
    else if (temperature >= 10)
    {
    Console.WriteLine("Mild.");
    }
    else
    {
    Console.WriteLine("Cold!");
    }
  3. switch expressions (C# 8.0 and later):
    This provides a more concise syntax for pattern matching, including range-based conditions.
    int age = 15;
    string ageGroup = age switch
    {
    int a when a < 13 => "Child",
    int a when a >= 13 && a < 18 => "Teenager",
    int a when a >= 18 && a < 65 => "Adult",
    _ => "Senior"
    };
    Console.WriteLine($"Age: {age}, Age Group: {ageGroup}");

Goal

Experiment with the above options to learn how to use them and implement the one which I like the best or performs the best in the application.

Acceptance Criteria: Demonstrate Performance testing of the three options above. Journal about the performance, experience, and preference. The final preference is implemented in code and PR'd into the main branch.

Metadata

Metadata

Assignees

Labels

discoveryThis issue is an opportunity to learn something.

Projects

Status

Backlog

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions