Top part of this answer is true for C# versions before 7. See below the line for an update for version 7
It's not possible. C# switches can only switch on exact equality:
Each case label specifies a constant value. Control is transferred to the switch section whose case label contains a constant value that matches the value of the switch expression,
You could replace it with a stack of if
/else
statements, or if you prefer, you can make something that looks quite compact, but some may frown on - a nest of conditional operators:
grade = examScore >= 90 ? "A" :
examScore >= 80 ? "B" :
examScore >= 70 ? "C" :
examScore >= 60 ? "D" :
"F";
With C# 7, switch
has been significantly enhanced, and it's now possible to apply more conditions within case
s, although it's still not as "clean" as the VB version. E.g. you could do something like:
switch (examScore)
{
case int es when es >= 90: grade = "A"; break;
case int es when es >= 80: grade = "B"; break;
case int es when es >= 70: grade = "C"; break;
case int es when es >= 60; grade = "D"; break;
default: grade = "F"; break;
}
Assuming that examScore
is an int
, this somewhat abuses the new "pattern matching on types" facility to be able to have something to say in the case
clause, and then using the when
clauses to apply arbitrary conditions to the newly introduced variable.