Can I somehow use a Switch statement here?

357mag

Well-known member
Joined
Mar 31, 2023
Messages
91
Programming Experience
3-5
I was wondering if this program could be written using a Switch statement instead. But how do you say "case 90 or greater". Or say "case 80 or greater".
Here is currently what I have:

C#:
private void btnCalculateGrade_Click(object sender, EventArgs e)
        {
            int x;

            x = Convert.ToInt32(txtGrade.Text);

            if (x >= 90)
            
                lblResult.Text = "Student Grade is A";
            
            else if (x >= 80)
                lblResult.Text = "Student Grade is B";

            else if (x >= 70)
                lblResult.Text = "Student Grade is C";

            else if (x >= 60)
                lblResult.Text = "Student Grade is D";

            else
                lblResult.Text = "Student Grade is F";   
        }
 
I found a similar post on this forum that talks about this. It doesn't appear that Visual Studio 2015 allows using relational operators with a switch.
 
This is done with a switch expression.

Example:
public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private void btnCalculateGrade_Click(object sender, EventArgs e)
    {
        if (int.TryParse(txtGrade.Text, out var grade))
        {
            var (letter, remarks) = grade.GetGradeWithRemarks();
            lblResult.Text = $"Student grade is {letter} which is {remarks}";
        }
        else
        {
            // Handle invalid input
        }
    }
}
public static class Extensions
{
    public static (string grade, string remarks) GetGradeWithRemarks(this int score) => score switch
    {
        >= 90 => ("A", "Great job"),
        >= 80 and < 90 => ("B", "Good"),
        >= 70 and < 80 => ("C", "Okay"),
        >= 60 and < 70 => ("D", "Better study"),
        >= 50 and < 60 => ("F", "You failed"),
        _ => throw new ArgumentOutOfRangeException(nameof(score), score, "Unexpected value")
    };
}
 
Back
Top Bottom