I’m just starting out learning C# and I’ve become stuck at something very basic.
For my first “app” I thought I’d go for something simple, so I decided for a BMI calculator.
The BMI is calculated into a decimal type which I’m now trying to use in a switch statement, but aparently decimal can’t be used in a switch?
What would be the C# solution for this:
decimal bmi = calculate_bmi(h, w);
switch (bmi) {
case < 18.5:
bmi_description = "underweight.";
break;
case > 25:
bmi_description = "overweight";
case > 30:
bmi_description = "very overweight";
case > 40:
bmi_description = "extreme overweight";
break;
}
The
switchstatement only supports integral types (enumerations are not listed but can be used withswitchstatements because they are backed by an integral type)(strings are also supported as pointed out by Changeling – see the comment for reference) and equality comparisons with constant values. Therefore you have to use someifstatements.By the way your switch statement is a bit weired because you are switching from less than to greater than and using fall-through without breaks. I think one should use only one type of comparison to make the code easier to understand or reorder the checks and do not use fall-through.