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")
    };
}
 
Switch case is considered faster and more readable than nested if-else statements. If-else statements require the compiler to check each statement to determine if a condition is met. Switch case is more efficient because it allows the compiler to determine only which case has to be executed.
If-else statements involving branching conditions under if and else statements. The code executes the if statement if a given condition is met, otherwise it executes the else statement. Here’s how the syntax looks a lot like the method you are using.
Example:
Example::
if (condition1) { //Body of if }
else if (condition2) { //Body of if }
else if (condition3) { //Body of if }
else { //default if all conditions return false }

  • In switch case, the expression in the switch statement decides which case to execute along with a break statement after each case. This allows the compiler to execute only the code in which the case condition is met, making it a more streamlined version of if-else. The syntax looks like this:
  • Switch Case Expression::
    switch ( variable )
    {
    case <variable value1>: //Do Something
    break;
    case <variable value2>://Do Something
    break;
    default: //Default will perform if all case’s fail
    break;
    }
 
Before C# 3 (or was it 4?), the C# compiler would just convert the switch statement into a series of if-else statements. I heard it straight from the dev teams all the way back then. After that, I was under the impression that the jump table generation by the C# compiler for switch statements only worked for integer types and other types that could be mapped to an integer. For strings, and other types, it would still fall back to implementing a series of if-else statements in the generated IL. I suppose the compiler has gotten better over the years. I've not looked too closely at the generated IL lately.
 
Back
Top Bottom